Edit on GitHub

Expressions

Every AST node in SQLGlot is represented by a subclass of Expression.

This module contains the implementation of all supported Expression types. Additionally, it exposes a number of helper functions, which are mainly used to programmatically build SQL expressions, such as sqlglot.expressions.select.


   1"""
   2## Expressions
   3
   4Every AST node in SQLGlot is represented by a subclass of `Expression`.
   5
   6This module contains the implementation of all supported `Expression` types. Additionally,
   7it exposes a number of helper functions, which are mainly used to programmatically build
   8SQL expressions, such as `sqlglot.expressions.select`.
   9
  10----
  11"""
  12
  13from __future__ import annotations
  14
  15import datetime
  16import math
  17import numbers
  18import re
  19import typing as t
  20from collections import deque
  21from copy import deepcopy
  22from enum import auto
  23
  24from sqlglot.errors import ParseError
  25from sqlglot.helper import (
  26    AutoName,
  27    camel_to_snake_case,
  28    ensure_collection,
  29    ensure_list,
  30    seq_get,
  31    split_num_words,
  32    subclasses,
  33)
  34from sqlglot.tokens import Token
  35
  36if t.TYPE_CHECKING:
  37    from sqlglot.dialects.dialect import DialectType
  38
  39E = t.TypeVar("E", bound="Expression")
  40
  41
  42class _Expression(type):
  43    def __new__(cls, clsname, bases, attrs):
  44        klass = super().__new__(cls, clsname, bases, attrs)
  45
  46        # When an Expression class is created, its key is automatically set to be
  47        # the lowercase version of the class' name.
  48        klass.key = clsname.lower()
  49
  50        # This is so that docstrings are not inherited in pdoc
  51        klass.__doc__ = klass.__doc__ or ""
  52
  53        return klass
  54
  55
  56class Expression(metaclass=_Expression):
  57    """
  58    The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary
  59    context, such as its child expressions, their names (arg keys), and whether a given child expression
  60    is optional or not.
  61
  62    Attributes:
  63        key: a unique key for each class in the Expression hierarchy. This is useful for hashing
  64            and representing expressions as strings.
  65        arg_types: determines what arguments (child nodes) are supported by an expression. It
  66            maps arg keys to booleans that indicate whether the corresponding args are optional.
  67
  68    Example:
  69        >>> class Foo(Expression):
  70        ...     arg_types = {"this": True, "expression": False}
  71
  72        The above definition informs us that Foo is an Expression that requires an argument called
  73        "this" and may also optionally receive an argument called "expression".
  74
  75    Args:
  76        args: a mapping used for retrieving the arguments of an expression, given their arg keys.
  77        parent: a reference to the parent expression (or None, in case of root expressions).
  78        arg_key: the arg key an expression is associated with, i.e. the name its parent expression
  79            uses to refer to it.
  80        comments: a list of comments that are associated with a given expression. This is used in
  81            order to preserve comments when transpiling SQL code.
  82        _type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the
  83            optimizer, in order to enable some transformations that require type information.
  84    """
  85
  86    key = "expression"
  87    arg_types = {"this": True}
  88    __slots__ = ("args", "parent", "arg_key", "comments", "_type", "_meta", "_hash")
  89
  90    def __init__(self, **args: t.Any):
  91        self.args: t.Dict[str, t.Any] = args
  92        self.parent: t.Optional[Expression] = None
  93        self.arg_key: t.Optional[str] = None
  94        self.comments: t.Optional[t.List[str]] = None
  95        self._type: t.Optional[DataType] = None
  96        self._meta: t.Optional[t.Dict[str, t.Any]] = None
  97        self._hash: t.Optional[int] = None
  98
  99        for arg_key, value in self.args.items():
 100            self._set_parent(arg_key, value)
 101
 102    def __eq__(self, other) -> bool:
 103        return type(self) is type(other) and hash(self) == hash(other)
 104
 105    @property
 106    def hashable_args(self) -> t.Any:
 107        args = (self.args.get(k) for k in self.arg_types)
 108
 109        return tuple(
 110            (tuple(_norm_arg(a) for a in arg) if arg else None)
 111            if type(arg) is list
 112            else (_norm_arg(arg) if arg is not None and arg is not False else None)
 113            for arg in args
 114        )
 115
 116    def __hash__(self) -> int:
 117        if self._hash is not None:
 118            return self._hash
 119
 120        return hash((self.__class__, self.hashable_args))
 121
 122    @property
 123    def this(self):
 124        """
 125        Retrieves the argument with key "this".
 126        """
 127        return self.args.get("this")
 128
 129    @property
 130    def expression(self):
 131        """
 132        Retrieves the argument with key "expression".
 133        """
 134        return self.args.get("expression")
 135
 136    @property
 137    def expressions(self):
 138        """
 139        Retrieves the argument with key "expressions".
 140        """
 141        return self.args.get("expressions") or []
 142
 143    def text(self, key) -> str:
 144        """
 145        Returns a textual representation of the argument corresponding to "key". This can only be used
 146        for args that are strings or leaf Expression instances, such as identifiers and literals.
 147        """
 148        field = self.args.get(key)
 149        if isinstance(field, str):
 150            return field
 151        if isinstance(field, (Identifier, Literal, Var)):
 152            return field.this
 153        if isinstance(field, (Star, Null)):
 154            return field.name
 155        return ""
 156
 157    @property
 158    def is_string(self) -> bool:
 159        """
 160        Checks whether a Literal expression is a string.
 161        """
 162        return isinstance(self, Literal) and self.args["is_string"]
 163
 164    @property
 165    def is_number(self) -> bool:
 166        """
 167        Checks whether a Literal expression is a number.
 168        """
 169        return isinstance(self, Literal) and not self.args["is_string"]
 170
 171    @property
 172    def is_int(self) -> bool:
 173        """
 174        Checks whether a Literal expression is an integer.
 175        """
 176        if self.is_number:
 177            try:
 178                int(self.name)
 179                return True
 180            except ValueError:
 181                pass
 182        return False
 183
 184    @property
 185    def is_star(self) -> bool:
 186        """Checks whether an expression is a star."""
 187        return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star))
 188
 189    @property
 190    def alias(self) -> str:
 191        """
 192        Returns the alias of the expression, or an empty string if it's not aliased.
 193        """
 194        if isinstance(self.args.get("alias"), TableAlias):
 195            return self.args["alias"].name
 196        return self.text("alias")
 197
 198    @property
 199    def name(self) -> str:
 200        return self.text("this")
 201
 202    @property
 203    def alias_or_name(self):
 204        return self.alias or self.name
 205
 206    @property
 207    def output_name(self):
 208        """
 209        Name of the output column if this expression is a selection.
 210
 211        If the Expression has no output name, an empty string is returned.
 212
 213        Example:
 214            >>> from sqlglot import parse_one
 215            >>> parse_one("SELECT a").expressions[0].output_name
 216            'a'
 217            >>> parse_one("SELECT b AS c").expressions[0].output_name
 218            'c'
 219            >>> parse_one("SELECT 1 + 2").expressions[0].output_name
 220            ''
 221        """
 222        return ""
 223
 224    @property
 225    def type(self) -> t.Optional[DataType]:
 226        return self._type
 227
 228    @type.setter
 229    def type(self, dtype: t.Optional[DataType | DataType.Type | str]) -> None:
 230        if dtype and not isinstance(dtype, DataType):
 231            dtype = DataType.build(dtype)
 232        self._type = dtype  # type: ignore
 233
 234    @property
 235    def meta(self) -> t.Dict[str, t.Any]:
 236        if self._meta is None:
 237            self._meta = {}
 238        return self._meta
 239
 240    def __deepcopy__(self, memo):
 241        copy = self.__class__(**deepcopy(self.args))
 242        if self.comments is not None:
 243            copy.comments = deepcopy(self.comments)
 244
 245        if self._type is not None:
 246            copy._type = self._type.copy()
 247
 248        if self._meta is not None:
 249            copy._meta = deepcopy(self._meta)
 250
 251        return copy
 252
 253    def copy(self):
 254        """
 255        Returns a deep copy of the expression.
 256        """
 257        new = deepcopy(self)
 258        new.parent = self.parent
 259        return new
 260
 261    def append(self, arg_key, value):
 262        """
 263        Appends value to arg_key if it's a list or sets it as a new list.
 264
 265        Args:
 266            arg_key (str): name of the list expression arg
 267            value (Any): value to append to the list
 268        """
 269        if not isinstance(self.args.get(arg_key), list):
 270            self.args[arg_key] = []
 271        self.args[arg_key].append(value)
 272        self._set_parent(arg_key, value)
 273
 274    def set(self, arg_key, value):
 275        """
 276        Sets `arg_key` to `value`.
 277
 278        Args:
 279            arg_key (str): name of the expression arg.
 280            value: value to set the arg to.
 281        """
 282        self.args[arg_key] = value
 283        self._set_parent(arg_key, value)
 284
 285    def _set_parent(self, arg_key, value):
 286        if hasattr(value, "parent"):
 287            value.parent = self
 288            value.arg_key = arg_key
 289        elif type(value) is list:
 290            for v in value:
 291                if hasattr(v, "parent"):
 292                    v.parent = self
 293                    v.arg_key = arg_key
 294
 295    @property
 296    def depth(self):
 297        """
 298        Returns the depth of this tree.
 299        """
 300        if self.parent:
 301            return self.parent.depth + 1
 302        return 0
 303
 304    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
 305        """Yields the key and expression for all arguments, exploding list args."""
 306        for k, vs in self.args.items():
 307            if type(vs) is list:
 308                for v in vs:
 309                    if hasattr(v, "parent"):
 310                        yield k, v
 311            else:
 312                if hasattr(vs, "parent"):
 313                    yield k, vs
 314
 315    def find(self, *expression_types: t.Type[E], bfs=True) -> E | None:
 316        """
 317        Returns the first node in this tree which matches at least one of
 318        the specified types.
 319
 320        Args:
 321            expression_types: the expression type(s) to match.
 322
 323        Returns:
 324            The node which matches the criteria or None if no such node was found.
 325        """
 326        return next(self.find_all(*expression_types, bfs=bfs), None)
 327
 328    def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]:
 329        """
 330        Returns a generator object which visits all nodes in this tree and only
 331        yields those that match at least one of the specified expression types.
 332
 333        Args:
 334            expression_types: the expression type(s) to match.
 335
 336        Returns:
 337            The generator object.
 338        """
 339        for expression, *_ in self.walk(bfs=bfs):
 340            if isinstance(expression, expression_types):
 341                yield expression
 342
 343    def find_ancestor(self, *expression_types: t.Type[E]) -> E | None:
 344        """
 345        Returns a nearest parent matching expression_types.
 346
 347        Args:
 348            expression_types: the expression type(s) to match.
 349
 350        Returns:
 351            The parent node.
 352        """
 353        ancestor = self.parent
 354        while ancestor and not isinstance(ancestor, expression_types):
 355            ancestor = ancestor.parent
 356        return t.cast(E, ancestor)
 357
 358    @property
 359    def parent_select(self):
 360        """
 361        Returns the parent select statement.
 362        """
 363        return self.find_ancestor(Select)
 364
 365    @property
 366    def same_parent(self):
 367        """Returns if the parent is the same class as itself."""
 368        return type(self.parent) is self.__class__
 369
 370    def root(self) -> Expression:
 371        """
 372        Returns the root expression of this tree.
 373        """
 374        expression = self
 375        while expression.parent:
 376            expression = expression.parent
 377        return expression
 378
 379    def walk(self, bfs=True, prune=None):
 380        """
 381        Returns a generator object which visits all nodes in this tree.
 382
 383        Args:
 384            bfs (bool): if set to True the BFS traversal order will be applied,
 385                otherwise the DFS traversal will be used instead.
 386            prune ((node, parent, arg_key) -> bool): callable that returns True if
 387                the generator should stop traversing this branch of the tree.
 388
 389        Returns:
 390            the generator object.
 391        """
 392        if bfs:
 393            yield from self.bfs(prune=prune)
 394        else:
 395            yield from self.dfs(prune=prune)
 396
 397    def dfs(self, parent=None, key=None, prune=None):
 398        """
 399        Returns a generator object which visits all nodes in this tree in
 400        the DFS (Depth-first) order.
 401
 402        Returns:
 403            The generator object.
 404        """
 405        parent = parent or self.parent
 406        yield self, parent, key
 407        if prune and prune(self, parent, key):
 408            return
 409
 410        for k, v in self.iter_expressions():
 411            yield from v.dfs(self, k, prune)
 412
 413    def bfs(self, prune=None):
 414        """
 415        Returns a generator object which visits all nodes in this tree in
 416        the BFS (Breadth-first) order.
 417
 418        Returns:
 419            The generator object.
 420        """
 421        queue = deque([(self, self.parent, None)])
 422
 423        while queue:
 424            item, parent, key = queue.popleft()
 425
 426            yield item, parent, key
 427            if prune and prune(item, parent, key):
 428                continue
 429
 430            for k, v in item.iter_expressions():
 431                queue.append((v, item, k))
 432
 433    def unnest(self):
 434        """
 435        Returns the first non parenthesis child or self.
 436        """
 437        expression = self
 438        while type(expression) is Paren:
 439            expression = expression.this
 440        return expression
 441
 442    def unalias(self):
 443        """
 444        Returns the inner expression if this is an Alias.
 445        """
 446        if isinstance(self, Alias):
 447            return self.this
 448        return self
 449
 450    def unnest_operands(self):
 451        """
 452        Returns unnested operands as a tuple.
 453        """
 454        return tuple(arg.unnest() for _, arg in self.iter_expressions())
 455
 456    def flatten(self, unnest=True):
 457        """
 458        Returns a generator which yields child nodes who's parents are the same class.
 459
 460        A AND B AND C -> [A, B, C]
 461        """
 462        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
 463            if not type(node) is self.__class__:
 464                yield node.unnest() if unnest else node
 465
 466    def __str__(self):
 467        return self.sql()
 468
 469    def __repr__(self):
 470        return self._to_s()
 471
 472    def sql(self, dialect: DialectType = None, **opts) -> str:
 473        """
 474        Returns SQL string representation of this tree.
 475
 476        Args:
 477            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
 478            opts: other `sqlglot.generator.Generator` options.
 479
 480        Returns:
 481            The SQL string.
 482        """
 483        from sqlglot.dialects import Dialect
 484
 485        return Dialect.get_or_raise(dialect)().generate(self, **opts)
 486
 487    def _to_s(self, hide_missing: bool = True, level: int = 0) -> str:
 488        indent = "" if not level else "\n"
 489        indent += "".join(["  "] * level)
 490        left = f"({self.key.upper()} "
 491
 492        args: t.Dict[str, t.Any] = {
 493            k: ", ".join(
 494                v._to_s(hide_missing=hide_missing, level=level + 1)
 495                if hasattr(v, "_to_s")
 496                else str(v)
 497                for v in ensure_list(vs)
 498                if v is not None
 499            )
 500            for k, vs in self.args.items()
 501        }
 502        args["comments"] = self.comments
 503        args["type"] = self.type
 504        args = {k: v for k, v in args.items() if v or not hide_missing}
 505
 506        right = ", ".join(f"{k}: {v}" for k, v in args.items())
 507        right += ")"
 508
 509        return indent + left + right
 510
 511    def transform(self, fun, *args, copy=True, **kwargs):
 512        """
 513        Recursively visits all tree nodes (excluding already transformed ones)
 514        and applies the given transformation function to each node.
 515
 516        Args:
 517            fun (function): a function which takes a node as an argument and returns a
 518                new transformed node or the same node without modifications. If the function
 519                returns None, then the corresponding node will be removed from the syntax tree.
 520            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
 521                modified in place.
 522
 523        Returns:
 524            The transformed tree.
 525        """
 526        node = self.copy() if copy else self
 527        new_node = fun(node, *args, **kwargs)
 528
 529        if new_node is None or not isinstance(new_node, Expression):
 530            return new_node
 531        if new_node is not node:
 532            new_node.parent = node.parent
 533            return new_node
 534
 535        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
 536        return new_node
 537
 538    def replace(self, expression):
 539        """
 540        Swap out this expression with a new expression.
 541
 542        For example::
 543
 544            >>> tree = Select().select("x").from_("tbl")
 545            >>> tree.find(Column).replace(Column(this="y"))
 546            (COLUMN this: y)
 547            >>> tree.sql()
 548            'SELECT y FROM tbl'
 549
 550        Args:
 551            expression (Expression|None): new node
 552
 553        Returns:
 554            The new expression or expressions.
 555        """
 556        if not self.parent:
 557            return expression
 558
 559        parent = self.parent
 560        self.parent = None
 561
 562        replace_children(parent, lambda child: expression if child is self else child)
 563        return expression
 564
 565    def pop(self):
 566        """
 567        Remove this expression from its AST.
 568
 569        Returns:
 570            The popped expression.
 571        """
 572        self.replace(None)
 573        return self
 574
 575    def assert_is(self, type_):
 576        """
 577        Assert that this `Expression` is an instance of `type_`.
 578
 579        If it is NOT an instance of `type_`, this raises an assertion error.
 580        Otherwise, this returns this expression.
 581
 582        Examples:
 583            This is useful for type security in chained expressions:
 584
 585            >>> import sqlglot
 586            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
 587            'SELECT x, z FROM y'
 588        """
 589        assert isinstance(self, type_)
 590        return self
 591
 592    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
 593        """
 594        Checks if this expression is valid (e.g. all mandatory args are set).
 595
 596        Args:
 597            args: a sequence of values that were used to instantiate a Func expression. This is used
 598                to check that the provided arguments don't exceed the function argument limit.
 599
 600        Returns:
 601            A list of error messages for all possible errors that were found.
 602        """
 603        errors: t.List[str] = []
 604
 605        for k in self.args:
 606            if k not in self.arg_types:
 607                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
 608        for k, mandatory in self.arg_types.items():
 609            v = self.args.get(k)
 610            if mandatory and (v is None or (isinstance(v, list) and not v)):
 611                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
 612
 613        if (
 614            args
 615            and isinstance(self, Func)
 616            and len(args) > len(self.arg_types)
 617            and not self.is_var_len_args
 618        ):
 619            errors.append(
 620                f"The number of provided arguments ({len(args)}) is greater than "
 621                f"the maximum number of supported arguments ({len(self.arg_types)})"
 622            )
 623
 624        return errors
 625
 626    def dump(self):
 627        """
 628        Dump this Expression to a JSON-serializable dict.
 629        """
 630        from sqlglot.serde import dump
 631
 632        return dump(self)
 633
 634    @classmethod
 635    def load(cls, obj):
 636        """
 637        Load a dict (as returned by `Expression.dump`) into an Expression instance.
 638        """
 639        from sqlglot.serde import load
 640
 641        return load(obj)
 642
 643
 644IntoType = t.Union[
 645    str,
 646    t.Type[Expression],
 647    t.Collection[t.Union[str, t.Type[Expression]]],
 648]
 649ExpOrStr = t.Union[str, Expression]
 650
 651
 652class Condition(Expression):
 653    def and_(self, *expressions, dialect=None, **opts):
 654        """
 655        AND this condition with one or multiple expressions.
 656
 657        Example:
 658            >>> condition("x=1").and_("y=1").sql()
 659            'x = 1 AND y = 1'
 660
 661        Args:
 662            *expressions (str | Expression): the SQL code strings to parse.
 663                If an `Expression` instance is passed, it will be used as-is.
 664            dialect (str): the dialect used to parse the input expression.
 665            opts (kwargs): other options to use to parse the input expressions.
 666
 667        Returns:
 668            And: the new condition.
 669        """
 670        return and_(self, *expressions, dialect=dialect, **opts)
 671
 672    def or_(self, *expressions, dialect=None, **opts):
 673        """
 674        OR this condition with one or multiple expressions.
 675
 676        Example:
 677            >>> condition("x=1").or_("y=1").sql()
 678            'x = 1 OR y = 1'
 679
 680        Args:
 681            *expressions (str | Expression): the SQL code strings to parse.
 682                If an `Expression` instance is passed, it will be used as-is.
 683            dialect (str): the dialect used to parse the input expression.
 684            opts (kwargs): other options to use to parse the input expressions.
 685
 686        Returns:
 687            Or: the new condition.
 688        """
 689        return or_(self, *expressions, dialect=dialect, **opts)
 690
 691    def not_(self):
 692        """
 693        Wrap this condition with NOT.
 694
 695        Example:
 696            >>> condition("x=1").not_().sql()
 697            'NOT x = 1'
 698
 699        Returns:
 700            Not: the new condition.
 701        """
 702        return not_(self)
 703
 704
 705class Predicate(Condition):
 706    """Relationships like x = y, x > 1, x >= y."""
 707
 708
 709class DerivedTable(Expression):
 710    @property
 711    def alias_column_names(self):
 712        table_alias = self.args.get("alias")
 713        if not table_alias:
 714            return []
 715        column_list = table_alias.assert_is(TableAlias).args.get("columns") or []
 716        return [c.name for c in column_list]
 717
 718    @property
 719    def selects(self):
 720        alias = self.args.get("alias")
 721
 722        if alias:
 723            return alias.columns
 724        return []
 725
 726    @property
 727    def named_selects(self):
 728        return [select.output_name for select in self.selects]
 729
 730
 731class Unionable(Expression):
 732    def union(self, expression, distinct=True, dialect=None, **opts):
 733        """
 734        Builds a UNION expression.
 735
 736        Example:
 737            >>> import sqlglot
 738            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
 739            'SELECT * FROM foo UNION SELECT * FROM bla'
 740
 741        Args:
 742            expression (str | Expression): the SQL code string.
 743                If an `Expression` instance is passed, it will be used as-is.
 744            distinct (bool): set the DISTINCT flag if and only if this is true.
 745            dialect (str): the dialect used to parse the input expression.
 746            opts (kwargs): other options to use to parse the input expressions.
 747        Returns:
 748            Union: the Union expression.
 749        """
 750        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
 751
 752    def intersect(self, expression, distinct=True, dialect=None, **opts):
 753        """
 754        Builds an INTERSECT expression.
 755
 756        Example:
 757            >>> import sqlglot
 758            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
 759            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
 760
 761        Args:
 762            expression (str | Expression): the SQL code string.
 763                If an `Expression` instance is passed, it will be used as-is.
 764            distinct (bool): set the DISTINCT flag if and only if this is true.
 765            dialect (str): the dialect used to parse the input expression.
 766            opts (kwargs): other options to use to parse the input expressions.
 767        Returns:
 768            Intersect: the Intersect expression
 769        """
 770        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
 771
 772    def except_(self, expression, distinct=True, dialect=None, **opts):
 773        """
 774        Builds an EXCEPT expression.
 775
 776        Example:
 777            >>> import sqlglot
 778            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
 779            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
 780
 781        Args:
 782            expression (str | Expression): the SQL code string.
 783                If an `Expression` instance is passed, it will be used as-is.
 784            distinct (bool): set the DISTINCT flag if and only if this is true.
 785            dialect (str): the dialect used to parse the input expression.
 786            opts (kwargs): other options to use to parse the input expressions.
 787        Returns:
 788            Except: the Except expression
 789        """
 790        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
 791
 792
 793class UDTF(DerivedTable, Unionable):
 794    pass
 795
 796
 797class Cache(Expression):
 798    arg_types = {
 799        "with": False,
 800        "this": True,
 801        "lazy": False,
 802        "options": False,
 803        "expression": False,
 804    }
 805
 806
 807class Uncache(Expression):
 808    arg_types = {"this": True, "exists": False}
 809
 810
 811class Create(Expression):
 812    arg_types = {
 813        "with": False,
 814        "this": True,
 815        "kind": True,
 816        "expression": False,
 817        "exists": False,
 818        "properties": False,
 819        "replace": False,
 820        "unique": False,
 821        "volatile": False,
 822        "indexes": False,
 823        "no_schema_binding": False,
 824        "begin": False,
 825    }
 826
 827
 828class Describe(Expression):
 829    arg_types = {"this": True, "kind": False}
 830
 831
 832class Pragma(Expression):
 833    pass
 834
 835
 836class Set(Expression):
 837    arg_types = {"expressions": False}
 838
 839
 840class SetItem(Expression):
 841    arg_types = {
 842        "this": False,
 843        "expressions": False,
 844        "kind": False,
 845        "collate": False,  # MySQL SET NAMES statement
 846        "global": False,
 847    }
 848
 849
 850class Show(Expression):
 851    arg_types = {
 852        "this": True,
 853        "target": False,
 854        "offset": False,
 855        "limit": False,
 856        "like": False,
 857        "where": False,
 858        "db": False,
 859        "full": False,
 860        "mutex": False,
 861        "query": False,
 862        "channel": False,
 863        "global": False,
 864        "log": False,
 865        "position": False,
 866        "types": False,
 867    }
 868
 869
 870class UserDefinedFunction(Expression):
 871    arg_types = {"this": True, "expressions": False, "wrapped": False}
 872
 873
 874class CharacterSet(Expression):
 875    arg_types = {"this": True, "default": False}
 876
 877
 878class With(Expression):
 879    arg_types = {"expressions": True, "recursive": False}
 880
 881    @property
 882    def recursive(self) -> bool:
 883        return bool(self.args.get("recursive"))
 884
 885
 886class WithinGroup(Expression):
 887    arg_types = {"this": True, "expression": False}
 888
 889
 890class CTE(DerivedTable):
 891    arg_types = {"this": True, "alias": True}
 892
 893
 894class TableAlias(Expression):
 895    arg_types = {"this": False, "columns": False}
 896
 897    @property
 898    def columns(self):
 899        return self.args.get("columns") or []
 900
 901
 902class BitString(Condition):
 903    pass
 904
 905
 906class HexString(Condition):
 907    pass
 908
 909
 910class ByteString(Condition):
 911    pass
 912
 913
 914class Column(Condition):
 915    arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False}
 916
 917    @property
 918    def table(self) -> str:
 919        return self.text("table")
 920
 921    @property
 922    def db(self) -> str:
 923        return self.text("db")
 924
 925    @property
 926    def catalog(self) -> str:
 927        return self.text("catalog")
 928
 929    @property
 930    def output_name(self) -> str:
 931        return self.name
 932
 933    @property
 934    def parts(self) -> t.List[Identifier]:
 935        """Return the parts of a column in order catalog, db, table, name."""
 936        return [part for part in reversed(list(self.args.values())) if part]
 937
 938    def to_dot(self) -> Dot:
 939        """Converts the column into a dot expression."""
 940        parts = self.parts
 941        parent = self.parent
 942
 943        while parent:
 944            if isinstance(parent, Dot):
 945                parts.append(parent.expression)
 946            parent = parent.parent
 947
 948        return Dot.build(parts)
 949
 950
 951class ColumnDef(Expression):
 952    arg_types = {
 953        "this": True,
 954        "kind": False,
 955        "constraints": False,
 956        "exists": False,
 957    }
 958
 959
 960class AlterColumn(Expression):
 961    arg_types = {
 962        "this": True,
 963        "dtype": False,
 964        "collate": False,
 965        "using": False,
 966        "default": False,
 967        "drop": False,
 968    }
 969
 970
 971class RenameTable(Expression):
 972    pass
 973
 974
 975class SetTag(Expression):
 976    arg_types = {"expressions": True, "unset": False}
 977
 978
 979class Comment(Expression):
 980    arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
 981
 982
 983class ColumnConstraint(Expression):
 984    arg_types = {"this": False, "kind": True}
 985
 986
 987class ColumnConstraintKind(Expression):
 988    pass
 989
 990
 991class AutoIncrementColumnConstraint(ColumnConstraintKind):
 992    pass
 993
 994
 995class CaseSpecificColumnConstraint(ColumnConstraintKind):
 996    arg_types = {"not_": True}
 997
 998
 999class CharacterSetColumnConstraint(ColumnConstraintKind):
1000    arg_types = {"this": True}
1001
1002
1003class CheckColumnConstraint(ColumnConstraintKind):
1004    pass
1005
1006
1007class CollateColumnConstraint(ColumnConstraintKind):
1008    pass
1009
1010
1011class CommentColumnConstraint(ColumnConstraintKind):
1012    pass
1013
1014
1015class CompressColumnConstraint(ColumnConstraintKind):
1016    pass
1017
1018
1019class DateFormatColumnConstraint(ColumnConstraintKind):
1020    arg_types = {"this": True}
1021
1022
1023class DefaultColumnConstraint(ColumnConstraintKind):
1024    pass
1025
1026
1027class EncodeColumnConstraint(ColumnConstraintKind):
1028    pass
1029
1030
1031class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1032    # this: True -> ALWAYS, this: False -> BY DEFAULT
1033    arg_types = {
1034        "this": False,
1035        "start": False,
1036        "increment": False,
1037        "minvalue": False,
1038        "maxvalue": False,
1039        "cycle": False,
1040    }
1041
1042
1043class InlineLengthColumnConstraint(ColumnConstraintKind):
1044    pass
1045
1046
1047class NotNullColumnConstraint(ColumnConstraintKind):
1048    arg_types = {"allow_null": False}
1049
1050
1051class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1052    arg_types = {"desc": False}
1053
1054
1055class TitleColumnConstraint(ColumnConstraintKind):
1056    pass
1057
1058
1059class UniqueColumnConstraint(ColumnConstraintKind):
1060    arg_types: t.Dict[str, t.Any] = {}
1061
1062
1063class UppercaseColumnConstraint(ColumnConstraintKind):
1064    arg_types: t.Dict[str, t.Any] = {}
1065
1066
1067class PathColumnConstraint(ColumnConstraintKind):
1068    pass
1069
1070
1071class Constraint(Expression):
1072    arg_types = {"this": True, "expressions": True}
1073
1074
1075class Delete(Expression):
1076    arg_types = {"with": False, "this": False, "using": False, "where": False, "returning": False}
1077
1078    def delete(
1079        self,
1080        table: ExpOrStr,
1081        dialect: DialectType = None,
1082        copy: bool = True,
1083        **opts,
1084    ) -> Delete:
1085        """
1086        Create a DELETE expression or replace the table on an existing DELETE expression.
1087
1088        Example:
1089            >>> delete("tbl").sql()
1090            'DELETE FROM tbl'
1091
1092        Args:
1093            table: the table from which to delete.
1094            dialect: the dialect used to parse the input expression.
1095            copy: if `False`, modify this expression instance in-place.
1096            opts: other options to use to parse the input expressions.
1097
1098        Returns:
1099            Delete: the modified expression.
1100        """
1101        return _apply_builder(
1102            expression=table,
1103            instance=self,
1104            arg="this",
1105            dialect=dialect,
1106            into=Table,
1107            copy=copy,
1108            **opts,
1109        )
1110
1111    def where(
1112        self,
1113        *expressions: ExpOrStr,
1114        append: bool = True,
1115        dialect: DialectType = None,
1116        copy: bool = True,
1117        **opts,
1118    ) -> Delete:
1119        """
1120        Append to or set the WHERE expressions.
1121
1122        Example:
1123            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1124            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1125
1126        Args:
1127            *expressions: the SQL code strings to parse.
1128                If an `Expression` instance is passed, it will be used as-is.
1129                Multiple expressions are combined with an AND operator.
1130            append: if `True`, AND the new expressions to any existing expression.
1131                Otherwise, this resets the expression.
1132            dialect: the dialect used to parse the input expressions.
1133            copy: if `False`, modify this expression instance in-place.
1134            opts: other options to use to parse the input expressions.
1135
1136        Returns:
1137            Delete: the modified expression.
1138        """
1139        return _apply_conjunction_builder(
1140            *expressions,
1141            instance=self,
1142            arg="where",
1143            append=append,
1144            into=Where,
1145            dialect=dialect,
1146            copy=copy,
1147            **opts,
1148        )
1149
1150    def returning(
1151        self,
1152        expression: ExpOrStr,
1153        dialect: DialectType = None,
1154        copy: bool = True,
1155        **opts,
1156    ) -> Delete:
1157        """
1158        Set the RETURNING expression. Not supported by all dialects.
1159
1160        Example:
1161            >>> delete("tbl").returning("*", dialect="postgres").sql()
1162            'DELETE FROM tbl RETURNING *'
1163
1164        Args:
1165            expression: the SQL code strings to parse.
1166                If an `Expression` instance is passed, it will be used as-is.
1167            dialect: the dialect used to parse the input expressions.
1168            copy: if `False`, modify this expression instance in-place.
1169            opts: other options to use to parse the input expressions.
1170
1171        Returns:
1172            Delete: the modified expression.
1173        """
1174        return _apply_builder(
1175            expression=expression,
1176            instance=self,
1177            arg="returning",
1178            prefix="RETURNING",
1179            dialect=dialect,
1180            copy=copy,
1181            into=Returning,
1182            **opts,
1183        )
1184
1185
1186class Drop(Expression):
1187    arg_types = {
1188        "this": False,
1189        "kind": False,
1190        "exists": False,
1191        "temporary": False,
1192        "materialized": False,
1193        "cascade": False,
1194    }
1195
1196
1197class Filter(Expression):
1198    arg_types = {"this": True, "expression": True}
1199
1200
1201class Check(Expression):
1202    pass
1203
1204
1205class Directory(Expression):
1206    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1207    arg_types = {"this": True, "local": False, "row_format": False}
1208
1209
1210class ForeignKey(Expression):
1211    arg_types = {
1212        "expressions": True,
1213        "reference": False,
1214        "delete": False,
1215        "update": False,
1216    }
1217
1218
1219class PrimaryKey(Expression):
1220    arg_types = {"expressions": True, "options": False}
1221
1222
1223class Unique(Expression):
1224    arg_types = {"expressions": True}
1225
1226
1227# https://www.postgresql.org/docs/9.1/sql-selectinto.html
1228# https://docs.aws.amazon.com/redshift/latest/dg/r_SELECT_INTO.html#r_SELECT_INTO-examples
1229class Into(Expression):
1230    arg_types = {"this": True, "temporary": False, "unlogged": False}
1231
1232
1233class From(Expression):
1234    arg_types = {"expressions": True}
1235
1236
1237class Having(Expression):
1238    pass
1239
1240
1241class Hint(Expression):
1242    arg_types = {"expressions": True}
1243
1244
1245class JoinHint(Expression):
1246    arg_types = {"this": True, "expressions": True}
1247
1248
1249class Identifier(Expression):
1250    arg_types = {"this": True, "quoted": False}
1251
1252    @property
1253    def quoted(self):
1254        return bool(self.args.get("quoted"))
1255
1256    @property
1257    def hashable_args(self) -> t.Any:
1258        if self.quoted and any(char.isupper() for char in self.this):
1259            return (self.this, self.quoted)
1260        return self.this.lower()
1261
1262    @property
1263    def output_name(self):
1264        return self.name
1265
1266
1267class Index(Expression):
1268    arg_types = {
1269        "this": False,
1270        "table": False,
1271        "where": False,
1272        "columns": False,
1273        "unique": False,
1274        "primary": False,
1275        "amp": False,  # teradata
1276    }
1277
1278
1279class Insert(Expression):
1280    arg_types = {
1281        "with": False,
1282        "this": True,
1283        "expression": False,
1284        "returning": False,
1285        "overwrite": False,
1286        "exists": False,
1287        "partition": False,
1288        "alternative": False,
1289    }
1290
1291
1292class Returning(Expression):
1293    arg_types = {"expressions": True}
1294
1295
1296# https://dev.mysql.com/doc/refman/8.0/en/charset-introducer.html
1297class Introducer(Expression):
1298    arg_types = {"this": True, "expression": True}
1299
1300
1301# national char, like n'utf8'
1302class National(Expression):
1303    pass
1304
1305
1306class LoadData(Expression):
1307    arg_types = {
1308        "this": True,
1309        "local": False,
1310        "overwrite": False,
1311        "inpath": True,
1312        "partition": False,
1313        "input_format": False,
1314        "serde": False,
1315    }
1316
1317
1318class Partition(Expression):
1319    arg_types = {"expressions": True}
1320
1321
1322class Fetch(Expression):
1323    arg_types = {"direction": False, "count": False}
1324
1325
1326class Group(Expression):
1327    arg_types = {
1328        "expressions": False,
1329        "grouping_sets": False,
1330        "cube": False,
1331        "rollup": False,
1332    }
1333
1334
1335class Lambda(Expression):
1336    arg_types = {"this": True, "expressions": True}
1337
1338
1339class Limit(Expression):
1340    arg_types = {"this": False, "expression": True}
1341
1342
1343class Literal(Condition):
1344    arg_types = {"this": True, "is_string": True}
1345
1346    @property
1347    def hashable_args(self) -> t.Any:
1348        return (self.this, self.args.get("is_string"))
1349
1350    @classmethod
1351    def number(cls, number) -> Literal:
1352        return cls(this=str(number), is_string=False)
1353
1354    @classmethod
1355    def string(cls, string) -> Literal:
1356        return cls(this=str(string), is_string=True)
1357
1358    @property
1359    def output_name(self):
1360        return self.name
1361
1362
1363class Join(Expression):
1364    arg_types = {
1365        "this": True,
1366        "on": False,
1367        "side": False,
1368        "kind": False,
1369        "using": False,
1370        "natural": False,
1371    }
1372
1373    @property
1374    def kind(self):
1375        return self.text("kind").upper()
1376
1377    @property
1378    def side(self):
1379        return self.text("side").upper()
1380
1381    @property
1382    def alias_or_name(self):
1383        return self.this.alias_or_name
1384
1385    def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1386        """
1387        Append to or set the ON expressions.
1388
1389        Example:
1390            >>> import sqlglot
1391            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1392            'JOIN x ON y = 1'
1393
1394        Args:
1395            *expressions (str | Expression): the SQL code strings to parse.
1396                If an `Expression` instance is passed, it will be used as-is.
1397                Multiple expressions are combined with an AND operator.
1398            append (bool): if `True`, AND the new expressions to any existing expression.
1399                Otherwise, this resets the expression.
1400            dialect (str): the dialect used to parse the input expressions.
1401            copy (bool): if `False`, modify this expression instance in-place.
1402            opts (kwargs): other options to use to parse the input expressions.
1403
1404        Returns:
1405            Join: the modified join expression.
1406        """
1407        join = _apply_conjunction_builder(
1408            *expressions,
1409            instance=self,
1410            arg="on",
1411            append=append,
1412            dialect=dialect,
1413            copy=copy,
1414            **opts,
1415        )
1416
1417        if join.kind == "CROSS":
1418            join.set("kind", None)
1419
1420        return join
1421
1422    def using(self, *expressions, append=True, dialect=None, copy=True, **opts):
1423        """
1424        Append to or set the USING expressions.
1425
1426        Example:
1427            >>> import sqlglot
1428            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1429            'JOIN x USING (foo, bla)'
1430
1431        Args:
1432            *expressions (str | Expression): the SQL code strings to parse.
1433                If an `Expression` instance is passed, it will be used as-is.
1434            append (bool): if `True`, concatenate the new expressions to the existing "using" list.
1435                Otherwise, this resets the expression.
1436            dialect (str): the dialect used to parse the input expressions.
1437            copy (bool): if `False`, modify this expression instance in-place.
1438            opts (kwargs): other options to use to parse the input expressions.
1439
1440        Returns:
1441            Join: the modified join expression.
1442        """
1443        join = _apply_list_builder(
1444            *expressions,
1445            instance=self,
1446            arg="using",
1447            append=append,
1448            dialect=dialect,
1449            copy=copy,
1450            **opts,
1451        )
1452
1453        if join.kind == "CROSS":
1454            join.set("kind", None)
1455
1456        return join
1457
1458
1459class Lateral(UDTF):
1460    arg_types = {"this": True, "view": False, "outer": False, "alias": False}
1461
1462
1463class MatchRecognize(Expression):
1464    arg_types = {
1465        "partition_by": False,
1466        "order": False,
1467        "measures": False,
1468        "rows": False,
1469        "after": False,
1470        "pattern": False,
1471        "define": False,
1472    }
1473
1474
1475# Clickhouse FROM FINAL modifier
1476# https://clickhouse.com/docs/en/sql-reference/statements/select/from/#final-modifier
1477class Final(Expression):
1478    pass
1479
1480
1481class Offset(Expression):
1482    arg_types = {"this": False, "expression": True}
1483
1484
1485class Order(Expression):
1486    arg_types = {"this": False, "expressions": True}
1487
1488
1489# hive specific sorts
1490# https://cwiki.apache.org/confluence/display/Hive/LanguageManual+SortBy
1491class Cluster(Order):
1492    pass
1493
1494
1495class Distribute(Order):
1496    pass
1497
1498
1499class Sort(Order):
1500    pass
1501
1502
1503class Ordered(Expression):
1504    arg_types = {"this": True, "desc": True, "nulls_first": True}
1505
1506
1507class Property(Expression):
1508    arg_types = {"this": True, "value": True}
1509
1510
1511class AfterJournalProperty(Property):
1512    arg_types = {"no": True, "dual": False, "local": False}
1513
1514
1515class AlgorithmProperty(Property):
1516    arg_types = {"this": True}
1517
1518
1519class AutoIncrementProperty(Property):
1520    arg_types = {"this": True}
1521
1522
1523class BlockCompressionProperty(Property):
1524    arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
1525
1526
1527class CharacterSetProperty(Property):
1528    arg_types = {"this": True, "default": True}
1529
1530
1531class ChecksumProperty(Property):
1532    arg_types = {"on": False, "default": False}
1533
1534
1535class CollateProperty(Property):
1536    arg_types = {"this": True}
1537
1538
1539class DataBlocksizeProperty(Property):
1540    arg_types = {"size": False, "units": False, "min": False, "default": False}
1541
1542
1543class DefinerProperty(Property):
1544    arg_types = {"this": True}
1545
1546
1547class DistKeyProperty(Property):
1548    arg_types = {"this": True}
1549
1550
1551class DistStyleProperty(Property):
1552    arg_types = {"this": True}
1553
1554
1555class EngineProperty(Property):
1556    arg_types = {"this": True}
1557
1558
1559class ExecuteAsProperty(Property):
1560    arg_types = {"this": True}
1561
1562
1563class ExternalProperty(Property):
1564    arg_types = {"this": False}
1565
1566
1567class FallbackProperty(Property):
1568    arg_types = {"no": True, "protection": False}
1569
1570
1571class FileFormatProperty(Property):
1572    arg_types = {"this": True}
1573
1574
1575class FreespaceProperty(Property):
1576    arg_types = {"this": True, "percent": False}
1577
1578
1579class IsolatedLoadingProperty(Property):
1580    arg_types = {
1581        "no": True,
1582        "concurrent": True,
1583        "for_all": True,
1584        "for_insert": True,
1585        "for_none": True,
1586    }
1587
1588
1589class JournalProperty(Property):
1590    arg_types = {"no": True, "dual": False, "before": False}
1591
1592
1593class LanguageProperty(Property):
1594    arg_types = {"this": True}
1595
1596
1597class LikeProperty(Property):
1598    arg_types = {"this": True, "expressions": False}
1599
1600
1601class LocationProperty(Property):
1602    arg_types = {"this": True}
1603
1604
1605class LockingProperty(Property):
1606    arg_types = {
1607        "this": False,
1608        "kind": True,
1609        "for_or_in": True,
1610        "lock_type": True,
1611        "override": False,
1612    }
1613
1614
1615class LogProperty(Property):
1616    arg_types = {"no": True}
1617
1618
1619class MaterializedProperty(Property):
1620    arg_types = {"this": False}
1621
1622
1623class MergeBlockRatioProperty(Property):
1624    arg_types = {"this": False, "no": False, "default": False, "percent": False}
1625
1626
1627class NoPrimaryIndexProperty(Property):
1628    arg_types = {"this": False}
1629
1630
1631class OnCommitProperty(Property):
1632    arg_type = {"this": False}
1633
1634
1635class PartitionedByProperty(Property):
1636    arg_types = {"this": True}
1637
1638
1639class ReturnsProperty(Property):
1640    arg_types = {"this": True, "is_table": False, "table": False}
1641
1642
1643class RowFormatDelimitedProperty(Property):
1644    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
1645    arg_types = {
1646        "fields": False,
1647        "escaped": False,
1648        "collection_items": False,
1649        "map_keys": False,
1650        "lines": False,
1651        "null": False,
1652        "serde": False,
1653    }
1654
1655
1656class RowFormatSerdeProperty(Property):
1657    arg_types = {"this": True}
1658
1659
1660class SchemaCommentProperty(Property):
1661    arg_types = {"this": True}
1662
1663
1664class SerdeProperties(Property):
1665    arg_types = {"expressions": True}
1666
1667
1668class SetProperty(Property):
1669    arg_types = {"multi": True}
1670
1671
1672class SortKeyProperty(Property):
1673    arg_types = {"this": True, "compound": False}
1674
1675
1676class SqlSecurityProperty(Property):
1677    arg_types = {"definer": True}
1678
1679
1680class TableFormatProperty(Property):
1681    arg_types = {"this": True}
1682
1683
1684class TemporaryProperty(Property):
1685    arg_types = {"global_": True}
1686
1687
1688class TransientProperty(Property):
1689    arg_types = {"this": False}
1690
1691
1692class VolatilityProperty(Property):
1693    arg_types = {"this": True}
1694
1695
1696class WithDataProperty(Property):
1697    arg_types = {"no": True, "statistics": False}
1698
1699
1700class WithJournalTableProperty(Property):
1701    arg_types = {"this": True}
1702
1703
1704class Properties(Expression):
1705    arg_types = {"expressions": True}
1706
1707    NAME_TO_PROPERTY = {
1708        "ALGORITHM": AlgorithmProperty,
1709        "AUTO_INCREMENT": AutoIncrementProperty,
1710        "CHARACTER SET": CharacterSetProperty,
1711        "COLLATE": CollateProperty,
1712        "COMMENT": SchemaCommentProperty,
1713        "DEFINER": DefinerProperty,
1714        "DISTKEY": DistKeyProperty,
1715        "DISTSTYLE": DistStyleProperty,
1716        "ENGINE": EngineProperty,
1717        "EXECUTE AS": ExecuteAsProperty,
1718        "FORMAT": FileFormatProperty,
1719        "LANGUAGE": LanguageProperty,
1720        "LOCATION": LocationProperty,
1721        "PARTITIONED_BY": PartitionedByProperty,
1722        "RETURNS": ReturnsProperty,
1723        "SORTKEY": SortKeyProperty,
1724        "TABLE_FORMAT": TableFormatProperty,
1725    }
1726
1727    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
1728
1729    # CREATE property locations
1730    # Form: schema specified
1731    #   create [POST_CREATE]
1732    #     table a [POST_NAME]
1733    #     (b int) [POST_SCHEMA]
1734    #     with ([POST_WITH])
1735    #     index (b) [POST_INDEX]
1736    #
1737    # Form: alias selection
1738    #   create [POST_CREATE]
1739    #     table a [POST_NAME]
1740    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
1741    #     index (c) [POST_INDEX]
1742    class Location(AutoName):
1743        POST_CREATE = auto()
1744        POST_NAME = auto()
1745        POST_SCHEMA = auto()
1746        POST_WITH = auto()
1747        POST_ALIAS = auto()
1748        POST_EXPRESSION = auto()
1749        POST_INDEX = auto()
1750        UNSUPPORTED = auto()
1751
1752    @classmethod
1753    def from_dict(cls, properties_dict) -> Properties:
1754        expressions = []
1755        for key, value in properties_dict.items():
1756            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
1757            if property_cls:
1758                expressions.append(property_cls(this=convert(value)))
1759            else:
1760                expressions.append(Property(this=Literal.string(key), value=convert(value)))
1761
1762        return cls(expressions=expressions)
1763
1764
1765class Qualify(Expression):
1766    pass
1767
1768
1769# https://www.ibm.com/docs/en/ias?topic=procedures-return-statement-in-sql
1770class Return(Expression):
1771    pass
1772
1773
1774class Reference(Expression):
1775    arg_types = {"this": True, "expressions": False, "options": False}
1776
1777
1778class Tuple(Expression):
1779    arg_types = {"expressions": False}
1780
1781
1782class Subqueryable(Unionable):
1783    def subquery(self, alias=None, copy=True) -> Subquery:
1784        """
1785        Convert this expression to an aliased expression that can be used as a Subquery.
1786
1787        Example:
1788            >>> subquery = Select().select("x").from_("tbl").subquery()
1789            >>> Select().select("x").from_(subquery).sql()
1790            'SELECT x FROM (SELECT x FROM tbl)'
1791
1792        Args:
1793            alias (str | Identifier): an optional alias for the subquery
1794            copy (bool): if `False`, modify this expression instance in-place.
1795
1796        Returns:
1797            Alias: the subquery
1798        """
1799        instance = _maybe_copy(self, copy)
1800        return Subquery(
1801            this=instance,
1802            alias=TableAlias(this=to_identifier(alias)) if alias else None,
1803        )
1804
1805    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1806        raise NotImplementedError
1807
1808    @property
1809    def ctes(self):
1810        with_ = self.args.get("with")
1811        if not with_:
1812            return []
1813        return with_.expressions
1814
1815    @property
1816    def selects(self):
1817        raise NotImplementedError("Subqueryable objects must implement `selects`")
1818
1819    @property
1820    def named_selects(self):
1821        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
1822
1823    def with_(
1824        self,
1825        alias,
1826        as_,
1827        recursive=None,
1828        append=True,
1829        dialect=None,
1830        copy=True,
1831        **opts,
1832    ):
1833        """
1834        Append to or set the common table expressions.
1835
1836        Example:
1837            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
1838            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
1839
1840        Args:
1841            alias (str | Expression): the SQL code string to parse as the table name.
1842                If an `Expression` instance is passed, this is used as-is.
1843            as_ (str | Expression): the SQL code string to parse as the table expression.
1844                If an `Expression` instance is passed, it will be used as-is.
1845            recursive (bool): set the RECURSIVE part of the expression. Defaults to `False`.
1846            append (bool): if `True`, add to any existing expressions.
1847                Otherwise, this resets the expressions.
1848            dialect (str): the dialect used to parse the input expression.
1849            copy (bool): if `False`, modify this expression instance in-place.
1850            opts (kwargs): other options to use to parse the input expressions.
1851
1852        Returns:
1853            Select: the modified expression.
1854        """
1855        alias_expression = maybe_parse(
1856            alias,
1857            dialect=dialect,
1858            into=TableAlias,
1859            **opts,
1860        )
1861        as_expression = maybe_parse(
1862            as_,
1863            dialect=dialect,
1864            **opts,
1865        )
1866        cte = CTE(
1867            this=as_expression,
1868            alias=alias_expression,
1869        )
1870        return _apply_child_list_builder(
1871            cte,
1872            instance=self,
1873            arg="with",
1874            append=append,
1875            copy=copy,
1876            into=With,
1877            properties={"recursive": recursive or False},
1878        )
1879
1880
1881QUERY_MODIFIERS = {
1882    "match": False,
1883    "laterals": False,
1884    "joins": False,
1885    "pivots": False,
1886    "where": False,
1887    "group": False,
1888    "having": False,
1889    "qualify": False,
1890    "windows": False,
1891    "distribute": False,
1892    "sort": False,
1893    "cluster": False,
1894    "order": False,
1895    "limit": False,
1896    "offset": False,
1897    "lock": False,
1898    "sample": False,
1899}
1900
1901
1902class Table(Expression):
1903    arg_types = {
1904        "this": True,
1905        "alias": False,
1906        "db": False,
1907        "catalog": False,
1908        "laterals": False,
1909        "joins": False,
1910        "pivots": False,
1911        "hints": False,
1912        "system_time": False,
1913    }
1914
1915    @property
1916    def db(self) -> str:
1917        return self.text("db")
1918
1919    @property
1920    def catalog(self) -> str:
1921        return self.text("catalog")
1922
1923
1924# See the TSQL "Querying data in a system-versioned temporal table" page
1925class SystemTime(Expression):
1926    arg_types = {
1927        "this": False,
1928        "expression": False,
1929        "kind": True,
1930    }
1931
1932
1933class Union(Subqueryable):
1934    arg_types = {
1935        "with": False,
1936        "this": True,
1937        "expression": True,
1938        "distinct": False,
1939        **QUERY_MODIFIERS,
1940    }
1941
1942    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1943        """
1944        Set the LIMIT expression.
1945
1946        Example:
1947            >>> select("1").union(select("1")).limit(1).sql()
1948            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
1949
1950        Args:
1951            expression (str | int | Expression): the SQL code string to parse.
1952                This can also be an integer.
1953                If a `Limit` instance is passed, this is used as-is.
1954                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
1955            dialect (str): the dialect used to parse the input expression.
1956            copy (bool): if `False`, modify this expression instance in-place.
1957            opts (kwargs): other options to use to parse the input expressions.
1958
1959        Returns:
1960            Select: The limited subqueryable.
1961        """
1962        return (
1963            select("*")
1964            .from_(self.subquery(alias="_l_0", copy=copy))
1965            .limit(expression, dialect=dialect, copy=False, **opts)
1966        )
1967
1968    def select(
1969        self,
1970        *expressions: ExpOrStr,
1971        append: bool = True,
1972        dialect: DialectType = None,
1973        copy: bool = True,
1974        **opts,
1975    ) -> Union:
1976        """Append to or set the SELECT of the union recursively.
1977
1978        Example:
1979            >>> from sqlglot import parse_one
1980            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
1981            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
1982
1983        Args:
1984            *expressions: the SQL code strings to parse.
1985                If an `Expression` instance is passed, it will be used as-is.
1986            append: if `True`, add to any existing expressions.
1987                Otherwise, this resets the expressions.
1988            dialect: the dialect used to parse the input expressions.
1989            copy: if `False`, modify this expression instance in-place.
1990            opts: other options to use to parse the input expressions.
1991
1992        Returns:
1993            Union: the modified expression.
1994        """
1995        this = self.copy() if copy else self
1996        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
1997        this.expression.unnest().select(
1998            *expressions, append=append, dialect=dialect, copy=False, **opts
1999        )
2000        return this
2001
2002    @property
2003    def named_selects(self):
2004        return self.this.unnest().named_selects
2005
2006    @property
2007    def is_star(self) -> bool:
2008        return self.this.is_star or self.expression.is_star
2009
2010    @property
2011    def selects(self):
2012        return self.this.unnest().selects
2013
2014    @property
2015    def left(self):
2016        return self.this
2017
2018    @property
2019    def right(self):
2020        return self.expression
2021
2022
2023class Except(Union):
2024    pass
2025
2026
2027class Intersect(Union):
2028    pass
2029
2030
2031class Unnest(UDTF):
2032    arg_types = {
2033        "expressions": True,
2034        "ordinality": False,
2035        "alias": False,
2036        "offset": False,
2037    }
2038
2039
2040class Update(Expression):
2041    arg_types = {
2042        "with": False,
2043        "this": False,
2044        "expressions": True,
2045        "from": False,
2046        "where": False,
2047        "returning": False,
2048    }
2049
2050
2051class Values(UDTF):
2052    arg_types = {
2053        "expressions": True,
2054        "ordinality": False,
2055        "alias": False,
2056    }
2057
2058
2059class Var(Expression):
2060    pass
2061
2062
2063class Schema(Expression):
2064    arg_types = {"this": False, "expressions": False}
2065
2066
2067# Used to represent the FOR UPDATE and FOR SHARE locking read types.
2068# https://dev.mysql.com/doc/refman/8.0/en/innodb-locking-reads.html
2069class Lock(Expression):
2070    arg_types = {"update": True}
2071
2072
2073class Select(Subqueryable):
2074    arg_types = {
2075        "with": False,
2076        "kind": False,
2077        "expressions": False,
2078        "hint": False,
2079        "distinct": False,
2080        "into": False,
2081        "from": False,
2082        **QUERY_MODIFIERS,
2083    }
2084
2085    def from_(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2086        """
2087        Set the FROM expression.
2088
2089        Example:
2090            >>> Select().from_("tbl").select("x").sql()
2091            'SELECT x FROM tbl'
2092
2093        Args:
2094            *expressions (str | Expression): the SQL code strings to parse.
2095                If a `From` instance is passed, this is used as-is.
2096                If another `Expression` instance is passed, it will be wrapped in a `From`.
2097            append (bool): if `True`, add to any existing expressions.
2098                Otherwise, this flattens all the `From` expression into a single expression.
2099            dialect (str): the dialect used to parse the input expression.
2100            copy (bool): if `False`, modify this expression instance in-place.
2101            opts (kwargs): other options to use to parse the input expressions.
2102
2103        Returns:
2104            Select: the modified expression.
2105        """
2106        return _apply_child_list_builder(
2107            *expressions,
2108            instance=self,
2109            arg="from",
2110            append=append,
2111            copy=copy,
2112            prefix="FROM",
2113            into=From,
2114            dialect=dialect,
2115            **opts,
2116        )
2117
2118    def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2119        """
2120        Set the GROUP BY expression.
2121
2122        Example:
2123            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2124            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2125
2126        Args:
2127            *expressions (str | Expression): the SQL code strings to parse.
2128                If a `Group` instance is passed, this is used as-is.
2129                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2130                If nothing is passed in then a group by is not applied to the expression
2131            append (bool): if `True`, add to any existing expressions.
2132                Otherwise, this flattens all the `Group` expression into a single expression.
2133            dialect (str): the dialect used to parse the input expression.
2134            copy (bool): if `False`, modify this expression instance in-place.
2135            opts (kwargs): other options to use to parse the input expressions.
2136
2137        Returns:
2138            Select: the modified expression.
2139        """
2140        if not expressions:
2141            return self if not copy else self.copy()
2142        return _apply_child_list_builder(
2143            *expressions,
2144            instance=self,
2145            arg="group",
2146            append=append,
2147            copy=copy,
2148            prefix="GROUP BY",
2149            into=Group,
2150            dialect=dialect,
2151            **opts,
2152        )
2153
2154    def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2155        """
2156        Set the ORDER BY expression.
2157
2158        Example:
2159            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2160            'SELECT x FROM tbl ORDER BY x DESC'
2161
2162        Args:
2163            *expressions (str | Expression): the SQL code strings to parse.
2164                If a `Group` instance is passed, this is used as-is.
2165                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2166            append (bool): if `True`, add to any existing expressions.
2167                Otherwise, this flattens all the `Order` expression into a single expression.
2168            dialect (str): the dialect used to parse the input expression.
2169            copy (bool): if `False`, modify this expression instance in-place.
2170            opts (kwargs): other options to use to parse the input expressions.
2171
2172        Returns:
2173            Select: the modified expression.
2174        """
2175        return _apply_child_list_builder(
2176            *expressions,
2177            instance=self,
2178            arg="order",
2179            append=append,
2180            copy=copy,
2181            prefix="ORDER BY",
2182            into=Order,
2183            dialect=dialect,
2184            **opts,
2185        )
2186
2187    def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2188        """
2189        Set the SORT BY expression.
2190
2191        Example:
2192            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql()
2193            'SELECT x FROM tbl SORT BY x DESC'
2194
2195        Args:
2196            *expressions (str | Expression): the SQL code strings to parse.
2197                If a `Group` instance is passed, this is used as-is.
2198                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2199            append (bool): if `True`, add to any existing expressions.
2200                Otherwise, this flattens all the `Order` expression into a single expression.
2201            dialect (str): the dialect used to parse the input expression.
2202            copy (bool): if `False`, modify this expression instance in-place.
2203            opts (kwargs): other options to use to parse the input expressions.
2204
2205        Returns:
2206            Select: the modified expression.
2207        """
2208        return _apply_child_list_builder(
2209            *expressions,
2210            instance=self,
2211            arg="sort",
2212            append=append,
2213            copy=copy,
2214            prefix="SORT BY",
2215            into=Sort,
2216            dialect=dialect,
2217            **opts,
2218        )
2219
2220    def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2221        """
2222        Set the CLUSTER BY expression.
2223
2224        Example:
2225            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql()
2226            'SELECT x FROM tbl CLUSTER BY x DESC'
2227
2228        Args:
2229            *expressions (str | Expression): the SQL code strings to parse.
2230                If a `Group` instance is passed, this is used as-is.
2231                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2232            append (bool): if `True`, add to any existing expressions.
2233                Otherwise, this flattens all the `Order` expression into a single expression.
2234            dialect (str): the dialect used to parse the input expression.
2235            copy (bool): if `False`, modify this expression instance in-place.
2236            opts (kwargs): other options to use to parse the input expressions.
2237
2238        Returns:
2239            Select: the modified expression.
2240        """
2241        return _apply_child_list_builder(
2242            *expressions,
2243            instance=self,
2244            arg="cluster",
2245            append=append,
2246            copy=copy,
2247            prefix="CLUSTER BY",
2248            into=Cluster,
2249            dialect=dialect,
2250            **opts,
2251        )
2252
2253    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2254        """
2255        Set the LIMIT expression.
2256
2257        Example:
2258            >>> Select().from_("tbl").select("x").limit(10).sql()
2259            'SELECT x FROM tbl LIMIT 10'
2260
2261        Args:
2262            expression (str | int | Expression): the SQL code string to parse.
2263                This can also be an integer.
2264                If a `Limit` instance is passed, this is used as-is.
2265                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2266            dialect (str): the dialect used to parse the input expression.
2267            copy (bool): if `False`, modify this expression instance in-place.
2268            opts (kwargs): other options to use to parse the input expressions.
2269
2270        Returns:
2271            Select: the modified expression.
2272        """
2273        return _apply_builder(
2274            expression=expression,
2275            instance=self,
2276            arg="limit",
2277            into=Limit,
2278            prefix="LIMIT",
2279            dialect=dialect,
2280            copy=copy,
2281            **opts,
2282        )
2283
2284    def offset(self, expression, dialect=None, copy=True, **opts) -> Select:
2285        """
2286        Set the OFFSET expression.
2287
2288        Example:
2289            >>> Select().from_("tbl").select("x").offset(10).sql()
2290            'SELECT x FROM tbl OFFSET 10'
2291
2292        Args:
2293            expression (str | int | Expression): the SQL code string to parse.
2294                This can also be an integer.
2295                If a `Offset` instance is passed, this is used as-is.
2296                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2297            dialect (str): the dialect used to parse the input expression.
2298            copy (bool): if `False`, modify this expression instance in-place.
2299            opts (kwargs): other options to use to parse the input expressions.
2300
2301        Returns:
2302            Select: the modified expression.
2303        """
2304        return _apply_builder(
2305            expression=expression,
2306            instance=self,
2307            arg="offset",
2308            into=Offset,
2309            prefix="OFFSET",
2310            dialect=dialect,
2311            copy=copy,
2312            **opts,
2313        )
2314
2315    def select(
2316        self,
2317        *expressions: ExpOrStr,
2318        append: bool = True,
2319        dialect: DialectType = None,
2320        copy: bool = True,
2321        **opts,
2322    ) -> Select:
2323        """
2324        Append to or set the SELECT expressions.
2325
2326        Example:
2327            >>> Select().select("x", "y").sql()
2328            'SELECT x, y'
2329
2330        Args:
2331            *expressions: the SQL code strings to parse.
2332                If an `Expression` instance is passed, it will be used as-is.
2333            append: if `True`, add to any existing expressions.
2334                Otherwise, this resets the expressions.
2335            dialect: the dialect used to parse the input expressions.
2336            copy: if `False`, modify this expression instance in-place.
2337            opts: other options to use to parse the input expressions.
2338
2339        Returns:
2340            Select: the modified expression.
2341        """
2342        return _apply_list_builder(
2343            *expressions,
2344            instance=self,
2345            arg="expressions",
2346            append=append,
2347            dialect=dialect,
2348            copy=copy,
2349            **opts,
2350        )
2351
2352    def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2353        """
2354        Append to or set the LATERAL expressions.
2355
2356        Example:
2357            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2358            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2359
2360        Args:
2361            *expressions (str | Expression): the SQL code strings to parse.
2362                If an `Expression` instance is passed, it will be used as-is.
2363            append (bool): if `True`, add to any existing expressions.
2364                Otherwise, this resets the expressions.
2365            dialect (str): the dialect used to parse the input expressions.
2366            copy (bool): if `False`, modify this expression instance in-place.
2367            opts (kwargs): other options to use to parse the input expressions.
2368
2369        Returns:
2370            Select: the modified expression.
2371        """
2372        return _apply_list_builder(
2373            *expressions,
2374            instance=self,
2375            arg="laterals",
2376            append=append,
2377            into=Lateral,
2378            prefix="LATERAL VIEW",
2379            dialect=dialect,
2380            copy=copy,
2381            **opts,
2382        )
2383
2384    def join(
2385        self,
2386        expression,
2387        on=None,
2388        using=None,
2389        append=True,
2390        join_type=None,
2391        join_alias=None,
2392        dialect=None,
2393        copy=True,
2394        **opts,
2395    ) -> Select:
2396        """
2397        Append to or set the JOIN expressions.
2398
2399        Example:
2400            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2401            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2402
2403            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2404            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2405
2406            Use `join_type` to change the type of join:
2407
2408            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2409            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2410
2411        Args:
2412            expression (str | Expression): the SQL code string to parse.
2413                If an `Expression` instance is passed, it will be used as-is.
2414            on (str | Expression): optionally specify the join "on" criteria as a SQL string.
2415                If an `Expression` instance is passed, it will be used as-is.
2416            using (str | Expression): optionally specify the join "using" criteria as a SQL string.
2417                If an `Expression` instance is passed, it will be used as-is.
2418            append (bool): if `True`, add to any existing expressions.
2419                Otherwise, this resets the expressions.
2420            join_type (str): If set, alter the parsed join type
2421            dialect (str): the dialect used to parse the input expressions.
2422            copy (bool): if `False`, modify this expression instance in-place.
2423            opts (kwargs): other options to use to parse the input expressions.
2424
2425        Returns:
2426            Select: the modified expression.
2427        """
2428        parse_args = {"dialect": dialect, **opts}
2429
2430        try:
2431            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2432        except ParseError:
2433            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2434
2435        join = expression if isinstance(expression, Join) else Join(this=expression)
2436
2437        if isinstance(join.this, Select):
2438            join.this.replace(join.this.subquery())
2439
2440        if join_type:
2441            natural: t.Optional[Token]
2442            side: t.Optional[Token]
2443            kind: t.Optional[Token]
2444
2445            natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2446
2447            if natural:
2448                join.set("natural", True)
2449            if side:
2450                join.set("side", side.text)
2451            if kind:
2452                join.set("kind", kind.text)
2453
2454        if on:
2455            on = and_(*ensure_collection(on), dialect=dialect, **opts)
2456            join.set("on", on)
2457
2458        if using:
2459            join = _apply_list_builder(
2460                *ensure_collection(using),
2461                instance=join,
2462                arg="using",
2463                append=append,
2464                copy=copy,
2465                **opts,
2466            )
2467
2468        if join_alias:
2469            join.set("this", alias_(join.this, join_alias, table=True))
2470        return _apply_list_builder(
2471            join,
2472            instance=self,
2473            arg="joins",
2474            append=append,
2475            copy=copy,
2476            **opts,
2477        )
2478
2479    def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2480        """
2481        Append to or set the WHERE expressions.
2482
2483        Example:
2484            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2485            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2486
2487        Args:
2488            *expressions (str | Expression): the SQL code strings to parse.
2489                If an `Expression` instance is passed, it will be used as-is.
2490                Multiple expressions are combined with an AND operator.
2491            append (bool): if `True`, AND the new expressions to any existing expression.
2492                Otherwise, this resets the expression.
2493            dialect (str): the dialect used to parse the input expressions.
2494            copy (bool): if `False`, modify this expression instance in-place.
2495            opts (kwargs): other options to use to parse the input expressions.
2496
2497        Returns:
2498            Select: the modified expression.
2499        """
2500        return _apply_conjunction_builder(
2501            *expressions,
2502            instance=self,
2503            arg="where",
2504            append=append,
2505            into=Where,
2506            dialect=dialect,
2507            copy=copy,
2508            **opts,
2509        )
2510
2511    def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2512        """
2513        Append to or set the HAVING expressions.
2514
2515        Example:
2516            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2517            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2518
2519        Args:
2520            *expressions (str | Expression): the SQL code strings to parse.
2521                If an `Expression` instance is passed, it will be used as-is.
2522                Multiple expressions are combined with an AND operator.
2523            append (bool): if `True`, AND the new expressions to any existing expression.
2524                Otherwise, this resets the expression.
2525            dialect (str): the dialect used to parse the input expressions.
2526            copy (bool): if `False`, modify this expression instance in-place.
2527            opts (kwargs): other options to use to parse the input expressions.
2528
2529        Returns:
2530            Select: the modified expression.
2531        """
2532        return _apply_conjunction_builder(
2533            *expressions,
2534            instance=self,
2535            arg="having",
2536            append=append,
2537            into=Having,
2538            dialect=dialect,
2539            copy=copy,
2540            **opts,
2541        )
2542
2543    def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2544        return _apply_list_builder(
2545            *expressions,
2546            instance=self,
2547            arg="windows",
2548            append=append,
2549            into=Window,
2550            dialect=dialect,
2551            copy=copy,
2552            **opts,
2553        )
2554
2555    def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2556        return _apply_conjunction_builder(
2557            *expressions,
2558            instance=self,
2559            arg="qualify",
2560            append=append,
2561            into=Qualify,
2562            dialect=dialect,
2563            copy=copy,
2564            **opts,
2565        )
2566
2567    def distinct(self, distinct=True, copy=True) -> Select:
2568        """
2569        Set the OFFSET expression.
2570
2571        Example:
2572            >>> Select().from_("tbl").select("x").distinct().sql()
2573            'SELECT DISTINCT x FROM tbl'
2574
2575        Args:
2576            distinct (bool): whether the Select should be distinct
2577            copy (bool): if `False`, modify this expression instance in-place.
2578
2579        Returns:
2580            Select: the modified expression.
2581        """
2582        instance = _maybe_copy(self, copy)
2583        instance.set("distinct", Distinct() if distinct else None)
2584        return instance
2585
2586    def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create:
2587        """
2588        Convert this expression to a CREATE TABLE AS statement.
2589
2590        Example:
2591            >>> Select().select("*").from_("tbl").ctas("x").sql()
2592            'CREATE TABLE x AS SELECT * FROM tbl'
2593
2594        Args:
2595            table (str | Expression): the SQL code string to parse as the table name.
2596                If another `Expression` instance is passed, it will be used as-is.
2597            properties (dict): an optional mapping of table properties
2598            dialect (str): the dialect used to parse the input table.
2599            copy (bool): if `False`, modify this expression instance in-place.
2600            opts (kwargs): other options to use to parse the input table.
2601
2602        Returns:
2603            Create: the CREATE TABLE AS expression
2604        """
2605        instance = _maybe_copy(self, copy)
2606        table_expression = maybe_parse(
2607            table,
2608            into=Table,
2609            dialect=dialect,
2610            **opts,
2611        )
2612        properties_expression = None
2613        if properties:
2614            properties_expression = Properties.from_dict(properties)
2615
2616        return Create(
2617            this=table_expression,
2618            kind="table",
2619            expression=instance,
2620            properties=properties_expression,
2621        )
2622
2623    def lock(self, update: bool = True, copy: bool = True) -> Select:
2624        """
2625        Set the locking read mode for this expression.
2626
2627        Examples:
2628            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
2629            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
2630
2631            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
2632            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
2633
2634        Args:
2635            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
2636            copy: if `False`, modify this expression instance in-place.
2637
2638        Returns:
2639            The modified expression.
2640        """
2641
2642        inst = _maybe_copy(self, copy)
2643        inst.set("lock", Lock(update=update))
2644
2645        return inst
2646
2647    @property
2648    def named_selects(self) -> t.List[str]:
2649        return [e.output_name for e in self.expressions if e.alias_or_name]
2650
2651    @property
2652    def is_star(self) -> bool:
2653        return any(expression.is_star for expression in self.expressions)
2654
2655    @property
2656    def selects(self) -> t.List[Expression]:
2657        return self.expressions
2658
2659
2660class Subquery(DerivedTable, Unionable):
2661    arg_types = {
2662        "this": True,
2663        "alias": False,
2664        "with": False,
2665        **QUERY_MODIFIERS,
2666    }
2667
2668    def unnest(self):
2669        """
2670        Returns the first non subquery.
2671        """
2672        expression = self
2673        while isinstance(expression, Subquery):
2674            expression = expression.this
2675        return expression
2676
2677    @property
2678    def is_star(self) -> bool:
2679        return self.this.is_star
2680
2681    @property
2682    def output_name(self):
2683        return self.alias
2684
2685
2686class TableSample(Expression):
2687    arg_types = {
2688        "this": False,
2689        "method": False,
2690        "bucket_numerator": False,
2691        "bucket_denominator": False,
2692        "bucket_field": False,
2693        "percent": False,
2694        "rows": False,
2695        "size": False,
2696        "seed": False,
2697        "kind": False,
2698    }
2699
2700
2701class Tag(Expression):
2702    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
2703
2704    arg_types = {
2705        "this": False,
2706        "prefix": False,
2707        "postfix": False,
2708    }
2709
2710
2711class Pivot(Expression):
2712    arg_types = {
2713        "this": False,
2714        "alias": False,
2715        "expressions": True,
2716        "field": True,
2717        "unpivot": True,
2718    }
2719
2720
2721class Window(Expression):
2722    arg_types = {
2723        "this": True,
2724        "partition_by": False,
2725        "order": False,
2726        "spec": False,
2727        "alias": False,
2728    }
2729
2730
2731class WindowSpec(Expression):
2732    arg_types = {
2733        "kind": False,
2734        "start": False,
2735        "start_side": False,
2736        "end": False,
2737        "end_side": False,
2738    }
2739
2740
2741class Where(Expression):
2742    pass
2743
2744
2745class Star(Expression):
2746    arg_types = {"except": False, "replace": False}
2747
2748    @property
2749    def name(self) -> str:
2750        return "*"
2751
2752    @property
2753    def output_name(self):
2754        return self.name
2755
2756
2757class Parameter(Expression):
2758    arg_types = {"this": True, "wrapped": False}
2759
2760
2761class SessionParameter(Expression):
2762    arg_types = {"this": True, "kind": False}
2763
2764
2765class Placeholder(Expression):
2766    arg_types = {"this": False}
2767
2768
2769class Null(Condition):
2770    arg_types: t.Dict[str, t.Any] = {}
2771
2772    @property
2773    def name(self) -> str:
2774        return "NULL"
2775
2776
2777class Boolean(Condition):
2778    pass
2779
2780
2781class DataType(Expression):
2782    arg_types = {
2783        "this": True,
2784        "expressions": False,
2785        "nested": False,
2786        "values": False,
2787        "prefix": False,
2788    }
2789
2790    class Type(AutoName):
2791        CHAR = auto()
2792        NCHAR = auto()
2793        VARCHAR = auto()
2794        NVARCHAR = auto()
2795        TEXT = auto()
2796        MEDIUMTEXT = auto()
2797        LONGTEXT = auto()
2798        MEDIUMBLOB = auto()
2799        LONGBLOB = auto()
2800        BINARY = auto()
2801        VARBINARY = auto()
2802        INT = auto()
2803        UINT = auto()
2804        TINYINT = auto()
2805        UTINYINT = auto()
2806        SMALLINT = auto()
2807        USMALLINT = auto()
2808        BIGINT = auto()
2809        UBIGINT = auto()
2810        FLOAT = auto()
2811        DOUBLE = auto()
2812        DECIMAL = auto()
2813        BIT = auto()
2814        BOOLEAN = auto()
2815        JSON = auto()
2816        JSONB = auto()
2817        INTERVAL = auto()
2818        TIME = auto()
2819        TIMESTAMP = auto()
2820        TIMESTAMPTZ = auto()
2821        TIMESTAMPLTZ = auto()
2822        DATE = auto()
2823        DATETIME = auto()
2824        ARRAY = auto()
2825        MAP = auto()
2826        UUID = auto()
2827        GEOGRAPHY = auto()
2828        GEOMETRY = auto()
2829        STRUCT = auto()
2830        NULLABLE = auto()
2831        HLLSKETCH = auto()
2832        HSTORE = auto()
2833        SUPER = auto()
2834        SERIAL = auto()
2835        SMALLSERIAL = auto()
2836        BIGSERIAL = auto()
2837        XML = auto()
2838        UNIQUEIDENTIFIER = auto()
2839        MONEY = auto()
2840        SMALLMONEY = auto()
2841        ROWVERSION = auto()
2842        IMAGE = auto()
2843        VARIANT = auto()
2844        OBJECT = auto()
2845        INET = auto()
2846        NULL = auto()
2847        UNKNOWN = auto()  # Sentinel value, useful for type annotation
2848
2849    TEXT_TYPES = {
2850        Type.CHAR,
2851        Type.NCHAR,
2852        Type.VARCHAR,
2853        Type.NVARCHAR,
2854        Type.TEXT,
2855    }
2856
2857    INTEGER_TYPES = {
2858        Type.INT,
2859        Type.TINYINT,
2860        Type.SMALLINT,
2861        Type.BIGINT,
2862    }
2863
2864    FLOAT_TYPES = {
2865        Type.FLOAT,
2866        Type.DOUBLE,
2867    }
2868
2869    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
2870
2871    TEMPORAL_TYPES = {
2872        Type.TIMESTAMP,
2873        Type.TIMESTAMPTZ,
2874        Type.TIMESTAMPLTZ,
2875        Type.DATE,
2876        Type.DATETIME,
2877    }
2878
2879    @classmethod
2880    def build(
2881        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
2882    ) -> DataType:
2883        from sqlglot import parse_one
2884
2885        if isinstance(dtype, str):
2886            if dtype.upper() in cls.Type.__members__:
2887                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()])
2888            else:
2889                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
2890            if data_type_exp is None:
2891                raise ValueError(f"Unparsable data type value: {dtype}")
2892        elif isinstance(dtype, DataType.Type):
2893            data_type_exp = DataType(this=dtype)
2894        elif isinstance(dtype, DataType):
2895            return dtype
2896        else:
2897            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
2898        return DataType(**{**data_type_exp.args, **kwargs})
2899
2900    def is_type(self, dtype: DataType.Type) -> bool:
2901        return self.this == dtype
2902
2903
2904# https://www.postgresql.org/docs/15/datatype-pseudo.html
2905class PseudoType(Expression):
2906    pass
2907
2908
2909class StructKwarg(Expression):
2910    arg_types = {"this": True, "expression": True}
2911
2912
2913# WHERE x <OP> EXISTS|ALL|ANY|SOME(SELECT ...)
2914class SubqueryPredicate(Predicate):
2915    pass
2916
2917
2918class All(SubqueryPredicate):
2919    pass
2920
2921
2922class Any(SubqueryPredicate):
2923    pass
2924
2925
2926class Exists(SubqueryPredicate):
2927    pass
2928
2929
2930# Commands to interact with the databases or engines. For most of the command
2931# expressions we parse whatever comes after the command's name as a string.
2932class Command(Expression):
2933    arg_types = {"this": True, "expression": False}
2934
2935
2936class Transaction(Expression):
2937    arg_types = {"this": False, "modes": False}
2938
2939
2940class Commit(Expression):
2941    arg_types = {"chain": False}
2942
2943
2944class Rollback(Expression):
2945    arg_types = {"savepoint": False}
2946
2947
2948class AlterTable(Expression):
2949    arg_types = {"this": True, "actions": True, "exists": False}
2950
2951
2952class AddConstraint(Expression):
2953    arg_types = {"this": False, "expression": False, "enforced": False}
2954
2955
2956class DropPartition(Expression):
2957    arg_types = {"expressions": True, "exists": False}
2958
2959
2960# Binary expressions like (ADD a b)
2961class Binary(Expression):
2962    arg_types = {"this": True, "expression": True}
2963
2964    @property
2965    def left(self):
2966        return self.this
2967
2968    @property
2969    def right(self):
2970        return self.expression
2971
2972
2973class Add(Binary):
2974    pass
2975
2976
2977class Connector(Binary, Condition):
2978    pass
2979
2980
2981class And(Connector):
2982    pass
2983
2984
2985class Or(Connector):
2986    pass
2987
2988
2989class BitwiseAnd(Binary):
2990    pass
2991
2992
2993class BitwiseLeftShift(Binary):
2994    pass
2995
2996
2997class BitwiseOr(Binary):
2998    pass
2999
3000
3001class BitwiseRightShift(Binary):
3002    pass
3003
3004
3005class BitwiseXor(Binary):
3006    pass
3007
3008
3009class Div(Binary):
3010    pass
3011
3012
3013class Overlaps(Binary):
3014    pass
3015
3016
3017class Dot(Binary):
3018    @property
3019    def name(self) -> str:
3020        return self.expression.name
3021
3022    @classmethod
3023    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3024        """Build a Dot object with a sequence of expressions."""
3025        if len(expressions) < 2:
3026            raise ValueError(f"Dot requires >= 2 expressions.")
3027
3028        a, b, *expressions = expressions
3029        dot = Dot(this=a, expression=b)
3030
3031        for expression in expressions:
3032            dot = Dot(this=dot, expression=expression)
3033
3034        return dot
3035
3036
3037class DPipe(Binary):
3038    pass
3039
3040
3041class EQ(Binary, Predicate):
3042    pass
3043
3044
3045class NullSafeEQ(Binary, Predicate):
3046    pass
3047
3048
3049class NullSafeNEQ(Binary, Predicate):
3050    pass
3051
3052
3053class Distance(Binary):
3054    pass
3055
3056
3057class Escape(Binary):
3058    pass
3059
3060
3061class Glob(Binary, Predicate):
3062    pass
3063
3064
3065class GT(Binary, Predicate):
3066    pass
3067
3068
3069class GTE(Binary, Predicate):
3070    pass
3071
3072
3073class ILike(Binary, Predicate):
3074    pass
3075
3076
3077class ILikeAny(Binary, Predicate):
3078    pass
3079
3080
3081class IntDiv(Binary):
3082    pass
3083
3084
3085class Is(Binary, Predicate):
3086    pass
3087
3088
3089class Kwarg(Binary):
3090    """Kwarg in special functions like func(kwarg => y)."""
3091
3092
3093class Like(Binary, Predicate):
3094    pass
3095
3096
3097class LikeAny(Binary, Predicate):
3098    pass
3099
3100
3101class LT(Binary, Predicate):
3102    pass
3103
3104
3105class LTE(Binary, Predicate):
3106    pass
3107
3108
3109class Mod(Binary):
3110    pass
3111
3112
3113class Mul(Binary):
3114    pass
3115
3116
3117class NEQ(Binary, Predicate):
3118    pass
3119
3120
3121class SimilarTo(Binary, Predicate):
3122    pass
3123
3124
3125class Slice(Binary):
3126    arg_types = {"this": False, "expression": False}
3127
3128
3129class Sub(Binary):
3130    pass
3131
3132
3133class ArrayOverlaps(Binary):
3134    pass
3135
3136
3137# Unary Expressions
3138# (NOT a)
3139class Unary(Expression):
3140    pass
3141
3142
3143class BitwiseNot(Unary):
3144    pass
3145
3146
3147class Not(Unary, Condition):
3148    pass
3149
3150
3151class Paren(Unary, Condition):
3152    arg_types = {"this": True, "with": False}
3153
3154
3155class Neg(Unary):
3156    pass
3157
3158
3159# Special Functions
3160class Alias(Expression):
3161    arg_types = {"this": True, "alias": False}
3162
3163    @property
3164    def output_name(self):
3165        return self.alias
3166
3167
3168class Aliases(Expression):
3169    arg_types = {"this": True, "expressions": True}
3170
3171    @property
3172    def aliases(self):
3173        return self.expressions
3174
3175
3176class AtTimeZone(Expression):
3177    arg_types = {"this": True, "zone": True}
3178
3179
3180class Between(Predicate):
3181    arg_types = {"this": True, "low": True, "high": True}
3182
3183
3184class Bracket(Condition):
3185    arg_types = {"this": True, "expressions": True}
3186
3187
3188class Distinct(Expression):
3189    arg_types = {"expressions": False, "on": False}
3190
3191
3192class In(Predicate):
3193    arg_types = {
3194        "this": True,
3195        "expressions": False,
3196        "query": False,
3197        "unnest": False,
3198        "field": False,
3199        "is_global": False,
3200    }
3201
3202
3203class TimeUnit(Expression):
3204    """Automatically converts unit arg into a var."""
3205
3206    arg_types = {"unit": False}
3207
3208    def __init__(self, **args):
3209        unit = args.get("unit")
3210        if isinstance(unit, (Column, Literal)):
3211            args["unit"] = Var(this=unit.name)
3212        elif isinstance(unit, Week):
3213            unit.set("this", Var(this=unit.this.name))
3214        super().__init__(**args)
3215
3216
3217class Interval(TimeUnit):
3218    arg_types = {"this": False, "unit": False}
3219
3220
3221class IgnoreNulls(Expression):
3222    pass
3223
3224
3225class RespectNulls(Expression):
3226    pass
3227
3228
3229# Functions
3230class Func(Condition):
3231    """
3232    The base class for all function expressions.
3233
3234    Attributes:
3235        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3236            treated as a variable length argument and the argument's value will be stored as a list.
3237        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3238            for this function expression. These values are used to map this node to a name during parsing
3239            as well as to provide the function's name during SQL string generation. By default the SQL
3240            name is set to the expression's class name transformed to snake case.
3241    """
3242
3243    is_var_len_args = False
3244
3245    @classmethod
3246    def from_arg_list(cls, args):
3247        if cls.is_var_len_args:
3248            all_arg_keys = list(cls.arg_types)
3249            # If this function supports variable length argument treat the last argument as such.
3250            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3251            num_non_var = len(non_var_len_arg_keys)
3252
3253            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3254            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3255        else:
3256            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3257
3258        return cls(**args_dict)
3259
3260    @classmethod
3261    def sql_names(cls):
3262        if cls is Func:
3263            raise NotImplementedError(
3264                "SQL name is only supported by concrete function implementations"
3265            )
3266        if "_sql_names" not in cls.__dict__:
3267            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3268        return cls._sql_names
3269
3270    @classmethod
3271    def sql_name(cls):
3272        return cls.sql_names()[0]
3273
3274    @classmethod
3275    def default_parser_mappings(cls):
3276        return {name: cls.from_arg_list for name in cls.sql_names()}
3277
3278
3279class AggFunc(Func):
3280    pass
3281
3282
3283class Abs(Func):
3284    pass
3285
3286
3287class Anonymous(Func):
3288    arg_types = {"this": True, "expressions": False}
3289    is_var_len_args = True
3290
3291
3292class ApproxDistinct(AggFunc):
3293    arg_types = {"this": True, "accuracy": False}
3294
3295
3296class Array(Func):
3297    arg_types = {"expressions": False}
3298    is_var_len_args = True
3299
3300
3301# https://docs.snowflake.com/en/sql-reference/functions/to_char
3302class ToChar(Func):
3303    arg_types = {"this": True, "format": False}
3304
3305
3306class GenerateSeries(Func):
3307    arg_types = {"start": True, "end": True, "step": False}
3308
3309
3310class ArrayAgg(AggFunc):
3311    pass
3312
3313
3314class ArrayAll(Func):
3315    arg_types = {"this": True, "expression": True}
3316
3317
3318class ArrayAny(Func):
3319    arg_types = {"this": True, "expression": True}
3320
3321
3322class ArrayConcat(Func):
3323    arg_types = {"this": True, "expressions": False}
3324    is_var_len_args = True
3325
3326
3327class ArrayContains(Binary, Func):
3328    pass
3329
3330
3331class ArrayContained(Binary):
3332    pass
3333
3334
3335class ArrayFilter(Func):
3336    arg_types = {"this": True, "expression": True}
3337    _sql_names = ["FILTER", "ARRAY_FILTER"]
3338
3339
3340class ArrayJoin(Func):
3341    arg_types = {"this": True, "expression": True, "null": False}
3342
3343
3344class ArraySize(Func):
3345    arg_types = {"this": True, "expression": False}
3346
3347
3348class ArraySort(Func):
3349    arg_types = {"this": True, "expression": False}
3350
3351
3352class ArraySum(Func):
3353    pass
3354
3355
3356class ArrayUnionAgg(AggFunc):
3357    pass
3358
3359
3360class Avg(AggFunc):
3361    pass
3362
3363
3364class AnyValue(AggFunc):
3365    pass
3366
3367
3368class Case(Func):
3369    arg_types = {"this": False, "ifs": True, "default": False}
3370
3371
3372class Cast(Func):
3373    arg_types = {"this": True, "to": True}
3374
3375    @property
3376    def name(self) -> str:
3377        return self.this.name
3378
3379    @property
3380    def to(self):
3381        return self.args["to"]
3382
3383    @property
3384    def output_name(self):
3385        return self.name
3386
3387    def is_type(self, dtype: DataType.Type) -> bool:
3388        return self.to.is_type(dtype)
3389
3390
3391class Collate(Binary):
3392    pass
3393
3394
3395class TryCast(Cast):
3396    pass
3397
3398
3399class Ceil(Func):
3400    arg_types = {"this": True, "decimals": False}
3401    _sql_names = ["CEIL", "CEILING"]
3402
3403
3404class Coalesce(Func):
3405    arg_types = {"this": True, "expressions": False}
3406    is_var_len_args = True
3407
3408
3409class Concat(Func):
3410    arg_types = {"expressions": True}
3411    is_var_len_args = True
3412
3413
3414class ConcatWs(Concat):
3415    _sql_names = ["CONCAT_WS"]
3416
3417
3418class Count(AggFunc):
3419    arg_types = {"this": False}
3420
3421
3422class CountIf(AggFunc):
3423    pass
3424
3425
3426class CurrentDate(Func):
3427    arg_types = {"this": False}
3428
3429
3430class CurrentDatetime(Func):
3431    arg_types = {"this": False}
3432
3433
3434class CurrentTime(Func):
3435    arg_types = {"this": False}
3436
3437
3438class CurrentTimestamp(Func):
3439    arg_types = {"this": False}
3440
3441
3442class DateAdd(Func, TimeUnit):
3443    arg_types = {"this": True, "expression": True, "unit": False}
3444
3445
3446class DateSub(Func, TimeUnit):
3447    arg_types = {"this": True, "expression": True, "unit": False}
3448
3449
3450class DateDiff(Func, TimeUnit):
3451    _sql_names = ["DATEDIFF", "DATE_DIFF"]
3452    arg_types = {"this": True, "expression": True, "unit": False}
3453
3454
3455class DateTrunc(Func):
3456    arg_types = {"unit": True, "this": True, "zone": False}
3457
3458
3459class DatetimeAdd(Func, TimeUnit):
3460    arg_types = {"this": True, "expression": True, "unit": False}
3461
3462
3463class DatetimeSub(Func, TimeUnit):
3464    arg_types = {"this": True, "expression": True, "unit": False}
3465
3466
3467class DatetimeDiff(Func, TimeUnit):
3468    arg_types = {"this": True, "expression": True, "unit": False}
3469
3470
3471class DatetimeTrunc(Func, TimeUnit):
3472    arg_types = {"this": True, "unit": True, "zone": False}
3473
3474
3475class DayOfWeek(Func):
3476    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
3477
3478
3479class DayOfMonth(Func):
3480    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
3481
3482
3483class DayOfYear(Func):
3484    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
3485
3486
3487class WeekOfYear(Func):
3488    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
3489
3490
3491class LastDateOfMonth(Func):
3492    pass
3493
3494
3495class Extract(Func):
3496    arg_types = {"this": True, "expression": True}
3497
3498
3499class TimestampAdd(Func, TimeUnit):
3500    arg_types = {"this": True, "expression": True, "unit": False}
3501
3502
3503class TimestampSub(Func, TimeUnit):
3504    arg_types = {"this": True, "expression": True, "unit": False}
3505
3506
3507class TimestampDiff(Func, TimeUnit):
3508    arg_types = {"this": True, "expression": True, "unit": False}
3509
3510
3511class TimestampTrunc(Func, TimeUnit):
3512    arg_types = {"this": True, "unit": True, "zone": False}
3513
3514
3515class TimeAdd(Func, TimeUnit):
3516    arg_types = {"this": True, "expression": True, "unit": False}
3517
3518
3519class TimeSub(Func, TimeUnit):
3520    arg_types = {"this": True, "expression": True, "unit": False}
3521
3522
3523class TimeDiff(Func, TimeUnit):
3524    arg_types = {"this": True, "expression": True, "unit": False}
3525
3526
3527class TimeTrunc(Func, TimeUnit):
3528    arg_types = {"this": True, "unit": True, "zone": False}
3529
3530
3531class DateFromParts(Func):
3532    _sql_names = ["DATEFROMPARTS"]
3533    arg_types = {"year": True, "month": True, "day": True}
3534
3535
3536class DateStrToDate(Func):
3537    pass
3538
3539
3540class DateToDateStr(Func):
3541    pass
3542
3543
3544class DateToDi(Func):
3545    pass
3546
3547
3548class Day(Func):
3549    pass
3550
3551
3552class Decode(Func):
3553    arg_types = {"this": True, "charset": True, "replace": False}
3554
3555
3556class DiToDate(Func):
3557    pass
3558
3559
3560class Encode(Func):
3561    arg_types = {"this": True, "charset": True}
3562
3563
3564class Exp(Func):
3565    pass
3566
3567
3568class Explode(Func):
3569    pass
3570
3571
3572class ExponentialTimeDecayedAvg(AggFunc):
3573    arg_types = {"this": True, "time": False, "decay": False}
3574
3575
3576class Floor(Func):
3577    arg_types = {"this": True, "decimals": False}
3578
3579
3580class Greatest(Func):
3581    arg_types = {"this": True, "expressions": False}
3582    is_var_len_args = True
3583
3584
3585class GroupConcat(Func):
3586    arg_types = {"this": True, "separator": False}
3587
3588
3589class GroupUniqArray(AggFunc):
3590    arg_types = {"this": True, "size": False}
3591
3592
3593class Hex(Func):
3594    pass
3595
3596
3597class Histogram(AggFunc):
3598    arg_types = {"this": True, "bins": False}
3599
3600
3601class If(Func):
3602    arg_types = {"this": True, "true": True, "false": False}
3603
3604
3605class IfNull(Func):
3606    arg_types = {"this": True, "expression": False}
3607    _sql_names = ["IFNULL", "NVL"]
3608
3609
3610class Initcap(Func):
3611    pass
3612
3613
3614class JSONBContains(Binary):
3615    _sql_names = ["JSONB_CONTAINS"]
3616
3617
3618class JSONExtract(Binary, Func):
3619    _sql_names = ["JSON_EXTRACT"]
3620
3621
3622class JSONExtractScalar(JSONExtract):
3623    _sql_names = ["JSON_EXTRACT_SCALAR"]
3624
3625
3626class JSONBExtract(JSONExtract):
3627    _sql_names = ["JSONB_EXTRACT"]
3628
3629
3630class JSONBExtractScalar(JSONExtract):
3631    _sql_names = ["JSONB_EXTRACT_SCALAR"]
3632
3633
3634class Least(Func):
3635    arg_types = {"expressions": False}
3636    is_var_len_args = True
3637
3638
3639class Length(Func):
3640    pass
3641
3642
3643class Levenshtein(Func):
3644    arg_types = {
3645        "this": True,
3646        "expression": False,
3647        "ins_cost": False,
3648        "del_cost": False,
3649        "sub_cost": False,
3650    }
3651
3652
3653class Ln(Func):
3654    pass
3655
3656
3657class Log(Func):
3658    arg_types = {"this": True, "expression": False}
3659
3660
3661class Log2(Func):
3662    pass
3663
3664
3665class Log10(Func):
3666    pass
3667
3668
3669class LogicalOr(AggFunc):
3670    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
3671
3672
3673class LogicalAnd(AggFunc):
3674    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
3675
3676
3677class Lower(Func):
3678    _sql_names = ["LOWER", "LCASE"]
3679
3680
3681class Map(Func):
3682    arg_types = {"keys": False, "values": False}
3683
3684
3685class VarMap(Func):
3686    arg_types = {"keys": True, "values": True}
3687    is_var_len_args = True
3688
3689
3690class Matches(Func):
3691    """Oracle/Snowflake decode.
3692    https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions040.htm
3693    Pattern matching MATCHES(value, search1, result1, ...searchN, resultN, else)
3694    """
3695
3696    arg_types = {"this": True, "expressions": True}
3697    is_var_len_args = True
3698
3699
3700class Max(AggFunc):
3701    arg_types = {"this": True, "expressions": False}
3702    is_var_len_args = True
3703
3704
3705class Min(AggFunc):
3706    arg_types = {"this": True, "expressions": False}
3707    is_var_len_args = True
3708
3709
3710class Month(Func):
3711    pass
3712
3713
3714class Nvl2(Func):
3715    arg_types = {"this": True, "true": True, "false": False}
3716
3717
3718class Posexplode(Func):
3719    pass
3720
3721
3722class Pow(Binary, Func):
3723    _sql_names = ["POWER", "POW"]
3724
3725
3726class PercentileCont(AggFunc):
3727    pass
3728
3729
3730class PercentileDisc(AggFunc):
3731    pass
3732
3733
3734class Quantile(AggFunc):
3735    arg_types = {"this": True, "quantile": True}
3736
3737
3738# Clickhouse-specific:
3739# https://clickhouse.com/docs/en/sql-reference/aggregate-functions/reference/quantiles/#quantiles
3740class Quantiles(AggFunc):
3741    arg_types = {"parameters": True, "expressions": True}
3742    is_var_len_args = True
3743
3744
3745class QuantileIf(AggFunc):
3746    arg_types = {"parameters": True, "expressions": True}
3747
3748
3749class ApproxQuantile(Quantile):
3750    arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
3751
3752
3753class RangeN(Func):
3754    arg_types = {"this": True, "expressions": True, "each": False}
3755
3756
3757class ReadCSV(Func):
3758    _sql_names = ["READ_CSV"]
3759    is_var_len_args = True
3760    arg_types = {"this": True, "expressions": False}
3761
3762
3763class Reduce(Func):
3764    arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
3765
3766
3767class RegexpExtract(Func):
3768    arg_types = {
3769        "this": True,
3770        "expression": True,
3771        "position": False,
3772        "occurrence": False,
3773        "group": False,
3774    }
3775
3776
3777class RegexpLike(Func):
3778    arg_types = {"this": True, "expression": True, "flag": False}
3779
3780
3781class RegexpILike(Func):
3782    arg_types = {"this": True, "expression": True, "flag": False}
3783
3784
3785class RegexpSplit(Func):
3786    arg_types = {"this": True, "expression": True}
3787
3788
3789class Repeat(Func):
3790    arg_types = {"this": True, "times": True}
3791
3792
3793class Round(Func):
3794    arg_types = {"this": True, "decimals": False}
3795
3796
3797class RowNumber(Func):
3798    arg_types: t.Dict[str, t.Any] = {}
3799
3800
3801class SafeDivide(Func):
3802    arg_types = {"this": True, "expression": True}
3803
3804
3805class SetAgg(AggFunc):
3806    pass
3807
3808
3809class SortArray(Func):
3810    arg_types = {"this": True, "asc": False}
3811
3812
3813class Split(Func):
3814    arg_types = {"this": True, "expression": True, "limit": False}
3815
3816
3817# Start may be omitted in the case of postgres
3818# https://www.postgresql.org/docs/9.1/functions-string.html @ Table 9-6
3819class Substring(Func):
3820    arg_types = {"this": True, "start": False, "length": False}
3821
3822
3823class StrPosition(Func):
3824    arg_types = {
3825        "this": True,
3826        "substr": True,
3827        "position": False,
3828        "instance": False,
3829    }
3830
3831
3832class StrToDate(Func):
3833    arg_types = {"this": True, "format": True}
3834
3835
3836class StrToTime(Func):
3837    arg_types = {"this": True, "format": True}
3838
3839
3840# Spark allows unix_timestamp()
3841# https://spark.apache.org/docs/3.1.3/api/python/reference/api/pyspark.sql.functions.unix_timestamp.html
3842class StrToUnix(Func):
3843    arg_types = {"this": False, "format": False}
3844
3845
3846class NumberToStr(Func):
3847    arg_types = {"this": True, "format": True}
3848
3849
3850class Struct(Func):
3851    arg_types = {"expressions": True}
3852    is_var_len_args = True
3853
3854
3855class StructExtract(Func):
3856    arg_types = {"this": True, "expression": True}
3857
3858
3859class Sum(AggFunc):
3860    pass
3861
3862
3863class Sqrt(Func):
3864    pass
3865
3866
3867class Stddev(AggFunc):
3868    pass
3869
3870
3871class StddevPop(AggFunc):
3872    pass
3873
3874
3875class StddevSamp(AggFunc):
3876    pass
3877
3878
3879class TimeToStr(Func):
3880    arg_types = {"this": True, "format": True}
3881
3882
3883class TimeToTimeStr(Func):
3884    pass
3885
3886
3887class TimeToUnix(Func):
3888    pass
3889
3890
3891class TimeStrToDate(Func):
3892    pass
3893
3894
3895class TimeStrToTime(Func):
3896    pass
3897
3898
3899class TimeStrToUnix(Func):
3900    pass
3901
3902
3903class Trim(Func):
3904    arg_types = {
3905        "this": True,
3906        "expression": False,
3907        "position": False,
3908        "collation": False,
3909    }
3910
3911
3912class TsOrDsAdd(Func, TimeUnit):
3913    arg_types = {"this": True, "expression": True, "unit": False}
3914
3915
3916class TsOrDsToDateStr(Func):
3917    pass
3918
3919
3920class TsOrDsToDate(Func):
3921    arg_types = {"this": True, "format": False}
3922
3923
3924class TsOrDiToDi(Func):
3925    pass
3926
3927
3928class Unhex(Func):
3929    pass
3930
3931
3932class UnixToStr(Func):
3933    arg_types = {"this": True, "format": False}
3934
3935
3936# https://prestodb.io/docs/current/functions/datetime.html
3937# presto has weird zone/hours/minutes
3938class UnixToTime(Func):
3939    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
3940
3941    SECONDS = Literal.string("seconds")
3942    MILLIS = Literal.string("millis")
3943    MICROS = Literal.string("micros")
3944
3945
3946class UnixToTimeStr(Func):
3947    pass
3948
3949
3950class Upper(Func):
3951    _sql_names = ["UPPER", "UCASE"]
3952
3953
3954class Variance(AggFunc):
3955    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
3956
3957
3958class VariancePop(AggFunc):
3959    _sql_names = ["VARIANCE_POP", "VAR_POP"]
3960
3961
3962class Week(Func):
3963    arg_types = {"this": True, "mode": False}
3964
3965
3966class XMLTable(Func):
3967    arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
3968
3969
3970class Year(Func):
3971    pass
3972
3973
3974class Use(Expression):
3975    arg_types = {"this": True, "kind": False}
3976
3977
3978class Merge(Expression):
3979    arg_types = {"this": True, "using": True, "on": True, "expressions": True}
3980
3981
3982class When(Func):
3983    arg_types = {"matched": True, "source": False, "condition": False, "then": True}
3984
3985
3986def _norm_arg(arg):
3987    return arg.lower() if type(arg) is str else arg
3988
3989
3990ALL_FUNCTIONS = subclasses(__name__, Func, (AggFunc, Anonymous, Func))
3991
3992
3993# Helpers
3994def maybe_parse(
3995    sql_or_expression: ExpOrStr,
3996    *,
3997    into: t.Optional[IntoType] = None,
3998    dialect: DialectType = None,
3999    prefix: t.Optional[str] = None,
4000    copy: bool = False,
4001    **opts,
4002) -> Expression:
4003    """Gracefully handle a possible string or expression.
4004
4005    Example:
4006        >>> maybe_parse("1")
4007        (LITERAL this: 1, is_string: False)
4008        >>> maybe_parse(to_identifier("x"))
4009        (IDENTIFIER this: x, quoted: False)
4010
4011    Args:
4012        sql_or_expression: the SQL code string or an expression
4013        into: the SQLGlot Expression to parse into
4014        dialect: the dialect used to parse the input expressions (in the case that an
4015            input expression is a SQL string).
4016        prefix: a string to prefix the sql with before it gets parsed
4017            (automatically includes a space)
4018        copy: whether or not to copy the expression.
4019        **opts: other options to use to parse the input expressions (again, in the case
4020            that an input expression is a SQL string).
4021
4022    Returns:
4023        Expression: the parsed or given expression.
4024    """
4025    if isinstance(sql_or_expression, Expression):
4026        if copy:
4027            return sql_or_expression.copy()
4028        return sql_or_expression
4029
4030    import sqlglot
4031
4032    sql = str(sql_or_expression)
4033    if prefix:
4034        sql = f"{prefix} {sql}"
4035    return sqlglot.parse_one(sql, read=dialect, into=into, **opts)
4036
4037
4038def _maybe_copy(instance, copy=True):
4039    return instance.copy() if copy else instance
4040
4041
4042def _is_wrong_expression(expression, into):
4043    return isinstance(expression, Expression) and not isinstance(expression, into)
4044
4045
4046def _apply_builder(
4047    expression,
4048    instance,
4049    arg,
4050    copy=True,
4051    prefix=None,
4052    into=None,
4053    dialect=None,
4054    **opts,
4055):
4056    if _is_wrong_expression(expression, into):
4057        expression = into(this=expression)
4058    instance = _maybe_copy(instance, copy)
4059    expression = maybe_parse(
4060        sql_or_expression=expression,
4061        prefix=prefix,
4062        into=into,
4063        dialect=dialect,
4064        **opts,
4065    )
4066    instance.set(arg, expression)
4067    return instance
4068
4069
4070def _apply_child_list_builder(
4071    *expressions,
4072    instance,
4073    arg,
4074    append=True,
4075    copy=True,
4076    prefix=None,
4077    into=None,
4078    dialect=None,
4079    properties=None,
4080    **opts,
4081):
4082    instance = _maybe_copy(instance, copy)
4083    parsed = []
4084    for expression in expressions:
4085        if _is_wrong_expression(expression, into):
4086            expression = into(expressions=[expression])
4087        expression = maybe_parse(
4088            expression,
4089            into=into,
4090            dialect=dialect,
4091            prefix=prefix,
4092            **opts,
4093        )
4094        parsed.extend(expression.expressions)
4095
4096    existing = instance.args.get(arg)
4097    if append and existing:
4098        parsed = existing.expressions + parsed
4099
4100    child = into(expressions=parsed)
4101    for k, v in (properties or {}).items():
4102        child.set(k, v)
4103    instance.set(arg, child)
4104    return instance
4105
4106
4107def _apply_list_builder(
4108    *expressions,
4109    instance,
4110    arg,
4111    append=True,
4112    copy=True,
4113    prefix=None,
4114    into=None,
4115    dialect=None,
4116    **opts,
4117):
4118    inst = _maybe_copy(instance, copy)
4119
4120    expressions = [
4121        maybe_parse(
4122            sql_or_expression=expression,
4123            into=into,
4124            prefix=prefix,
4125            dialect=dialect,
4126            **opts,
4127        )
4128        for expression in expressions
4129    ]
4130
4131    existing_expressions = inst.args.get(arg)
4132    if append and existing_expressions:
4133        expressions = existing_expressions + expressions
4134
4135    inst.set(arg, expressions)
4136    return inst
4137
4138
4139def _apply_conjunction_builder(
4140    *expressions,
4141    instance,
4142    arg,
4143    into=None,
4144    append=True,
4145    copy=True,
4146    dialect=None,
4147    **opts,
4148):
4149    expressions = [exp for exp in expressions if exp is not None and exp != ""]
4150    if not expressions:
4151        return instance
4152
4153    inst = _maybe_copy(instance, copy)
4154
4155    existing = inst.args.get(arg)
4156    if append and existing is not None:
4157        expressions = [existing.this if into else existing] + list(expressions)
4158
4159    node = and_(*expressions, dialect=dialect, **opts)
4160
4161    inst.set(arg, into(this=node) if into else node)
4162    return inst
4163
4164
4165def _combine(expressions, operator, dialect=None, **opts):
4166    expressions = [condition(expression, dialect=dialect, **opts) for expression in expressions]
4167    this = expressions[0]
4168    if expressions[1:]:
4169        this = _wrap_operator(this)
4170    for expression in expressions[1:]:
4171        this = operator(this=this, expression=_wrap_operator(expression))
4172    return this
4173
4174
4175def _wrap_operator(expression):
4176    if isinstance(expression, (And, Or, Not)):
4177        expression = Paren(this=expression)
4178    return expression
4179
4180
4181def union(left, right, distinct=True, dialect=None, **opts):
4182    """
4183    Initializes a syntax tree from one UNION expression.
4184
4185    Example:
4186        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
4187        'SELECT * FROM foo UNION SELECT * FROM bla'
4188
4189    Args:
4190        left (str | Expression): the SQL code string corresponding to the left-hand side.
4191            If an `Expression` instance is passed, it will be used as-is.
4192        right (str | Expression): the SQL code string corresponding to the right-hand side.
4193            If an `Expression` instance is passed, it will be used as-is.
4194        distinct (bool): set the DISTINCT flag if and only if this is true.
4195        dialect (str): the dialect used to parse the input expression.
4196        opts (kwargs): other options to use to parse the input expressions.
4197    Returns:
4198        Union: the syntax tree for the UNION expression.
4199    """
4200    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4201    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4202
4203    return Union(this=left, expression=right, distinct=distinct)
4204
4205
4206def intersect(left, right, distinct=True, dialect=None, **opts):
4207    """
4208    Initializes a syntax tree from one INTERSECT expression.
4209
4210    Example:
4211        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
4212        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
4213
4214    Args:
4215        left (str | Expression): the SQL code string corresponding to the left-hand side.
4216            If an `Expression` instance is passed, it will be used as-is.
4217        right (str | Expression): the SQL code string corresponding to the right-hand side.
4218            If an `Expression` instance is passed, it will be used as-is.
4219        distinct (bool): set the DISTINCT flag if and only if this is true.
4220        dialect (str): the dialect used to parse the input expression.
4221        opts (kwargs): other options to use to parse the input expressions.
4222    Returns:
4223        Intersect: the syntax tree for the INTERSECT expression.
4224    """
4225    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4226    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4227
4228    return Intersect(this=left, expression=right, distinct=distinct)
4229
4230
4231def except_(left, right, distinct=True, dialect=None, **opts):
4232    """
4233    Initializes a syntax tree from one EXCEPT expression.
4234
4235    Example:
4236        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
4237        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
4238
4239    Args:
4240        left (str | Expression): the SQL code string corresponding to the left-hand side.
4241            If an `Expression` instance is passed, it will be used as-is.
4242        right (str | Expression): the SQL code string corresponding to the right-hand side.
4243            If an `Expression` instance is passed, it will be used as-is.
4244        distinct (bool): set the DISTINCT flag if and only if this is true.
4245        dialect (str): the dialect used to parse the input expression.
4246        opts (kwargs): other options to use to parse the input expressions.
4247    Returns:
4248        Except: the syntax tree for the EXCEPT statement.
4249    """
4250    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4251    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4252
4253    return Except(this=left, expression=right, distinct=distinct)
4254
4255
4256def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4257    """
4258    Initializes a syntax tree from one or multiple SELECT expressions.
4259
4260    Example:
4261        >>> select("col1", "col2").from_("tbl").sql()
4262        'SELECT col1, col2 FROM tbl'
4263
4264    Args:
4265        *expressions: the SQL code string to parse as the expressions of a
4266            SELECT statement. If an Expression instance is passed, this is used as-is.
4267        dialect: the dialect used to parse the input expressions (in the case that an
4268            input expression is a SQL string).
4269        **opts: other options to use to parse the input expressions (again, in the case
4270            that an input expression is a SQL string).
4271
4272    Returns:
4273        Select: the syntax tree for the SELECT statement.
4274    """
4275    return Select().select(*expressions, dialect=dialect, **opts)
4276
4277
4278def from_(*expressions, dialect=None, **opts) -> Select:
4279    """
4280    Initializes a syntax tree from a FROM expression.
4281
4282    Example:
4283        >>> from_("tbl").select("col1", "col2").sql()
4284        'SELECT col1, col2 FROM tbl'
4285
4286    Args:
4287        *expressions (str | Expression): the SQL code string to parse as the FROM expressions of a
4288            SELECT statement. If an Expression instance is passed, this is used as-is.
4289        dialect (str): the dialect used to parse the input expression (in the case that the
4290            input expression is a SQL string).
4291        **opts: other options to use to parse the input expressions (again, in the case
4292            that the input expression is a SQL string).
4293
4294    Returns:
4295        Select: the syntax tree for the SELECT statement.
4296    """
4297    return Select().from_(*expressions, dialect=dialect, **opts)
4298
4299
4300def update(
4301    table: str | Table,
4302    properties: dict,
4303    where: t.Optional[ExpOrStr] = None,
4304    from_: t.Optional[ExpOrStr] = None,
4305    dialect: DialectType = None,
4306    **opts,
4307) -> Update:
4308    """
4309    Creates an update statement.
4310
4311    Example:
4312        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
4313        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
4314
4315    Args:
4316        *properties: dictionary of properties to set which are
4317            auto converted to sql objects eg None -> NULL
4318        where: sql conditional parsed into a WHERE statement
4319        from_: sql statement parsed into a FROM statement
4320        dialect: the dialect used to parse the input expressions.
4321        **opts: other options to use to parse the input expressions.
4322
4323    Returns:
4324        Update: the syntax tree for the UPDATE statement.
4325    """
4326    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
4327    update_expr.set(
4328        "expressions",
4329        [
4330            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
4331            for k, v in properties.items()
4332        ],
4333    )
4334    if from_:
4335        update_expr.set(
4336            "from",
4337            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
4338        )
4339    if isinstance(where, Condition):
4340        where = Where(this=where)
4341    if where:
4342        update_expr.set(
4343            "where",
4344            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
4345        )
4346    return update_expr
4347
4348
4349def delete(
4350    table: ExpOrStr,
4351    where: t.Optional[ExpOrStr] = None,
4352    returning: t.Optional[ExpOrStr] = None,
4353    dialect: DialectType = None,
4354    **opts,
4355) -> Delete:
4356    """
4357    Builds a delete statement.
4358
4359    Example:
4360        >>> delete("my_table", where="id > 1").sql()
4361        'DELETE FROM my_table WHERE id > 1'
4362
4363    Args:
4364        where: sql conditional parsed into a WHERE statement
4365        returning: sql conditional parsed into a RETURNING statement
4366        dialect: the dialect used to parse the input expressions.
4367        **opts: other options to use to parse the input expressions.
4368
4369    Returns:
4370        Delete: the syntax tree for the DELETE statement.
4371    """
4372    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
4373    if where:
4374        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
4375    if returning:
4376        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
4377    return delete_expr
4378
4379
4380def condition(expression, dialect=None, **opts) -> Condition:
4381    """
4382    Initialize a logical condition expression.
4383
4384    Example:
4385        >>> condition("x=1").sql()
4386        'x = 1'
4387
4388        This is helpful for composing larger logical syntax trees:
4389        >>> where = condition("x=1")
4390        >>> where = where.and_("y=1")
4391        >>> Select().from_("tbl").select("*").where(where).sql()
4392        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
4393
4394    Args:
4395        *expression (str | Expression): the SQL code string to parse.
4396            If an Expression instance is passed, this is used as-is.
4397        dialect (str): the dialect used to parse the input expression (in the case that the
4398            input expression is a SQL string).
4399        **opts: other options to use to parse the input expressions (again, in the case
4400            that the input expression is a SQL string).
4401
4402    Returns:
4403        Condition: the expression
4404    """
4405    return maybe_parse(  # type: ignore
4406        expression,
4407        into=Condition,
4408        dialect=dialect,
4409        **opts,
4410    )
4411
4412
4413def and_(*expressions, dialect=None, **opts) -> And:
4414    """
4415    Combine multiple conditions with an AND logical operator.
4416
4417    Example:
4418        >>> and_("x=1", and_("y=1", "z=1")).sql()
4419        'x = 1 AND (y = 1 AND z = 1)'
4420
4421    Args:
4422        *expressions (str | Expression): the SQL code strings to parse.
4423            If an Expression instance is passed, this is used as-is.
4424        dialect (str): the dialect used to parse the input expression.
4425        **opts: other options to use to parse the input expressions.
4426
4427    Returns:
4428        And: the new condition
4429    """
4430    return _combine(expressions, And, dialect, **opts)
4431
4432
4433def or_(*expressions, dialect=None, **opts) -> Or:
4434    """
4435    Combine multiple conditions with an OR logical operator.
4436
4437    Example:
4438        >>> or_("x=1", or_("y=1", "z=1")).sql()
4439        'x = 1 OR (y = 1 OR z = 1)'
4440
4441    Args:
4442        *expressions (str | Expression): the SQL code strings to parse.
4443            If an Expression instance is passed, this is used as-is.
4444        dialect (str): the dialect used to parse the input expression.
4445        **opts: other options to use to parse the input expressions.
4446
4447    Returns:
4448        Or: the new condition
4449    """
4450    return _combine(expressions, Or, dialect, **opts)
4451
4452
4453def not_(expression, dialect=None, **opts) -> Not:
4454    """
4455    Wrap a condition with a NOT operator.
4456
4457    Example:
4458        >>> not_("this_suit='black'").sql()
4459        "NOT this_suit = 'black'"
4460
4461    Args:
4462        expression (str | Expression): the SQL code strings to parse.
4463            If an Expression instance is passed, this is used as-is.
4464        dialect (str): the dialect used to parse the input expression.
4465        **opts: other options to use to parse the input expressions.
4466
4467    Returns:
4468        Not: the new condition
4469    """
4470    this = condition(
4471        expression,
4472        dialect=dialect,
4473        **opts,
4474    )
4475    return Not(this=_wrap_operator(this))
4476
4477
4478def paren(expression) -> Paren:
4479    return Paren(this=expression)
4480
4481
4482SAFE_IDENTIFIER_RE = re.compile(r"^[_a-zA-Z][\w]*$")
4483
4484
4485@t.overload
4486def to_identifier(name: None, quoted: t.Optional[bool] = None) -> None:
4487    ...
4488
4489
4490@t.overload
4491def to_identifier(name: str | Identifier, quoted: t.Optional[bool] = None) -> Identifier:
4492    ...
4493
4494
4495def to_identifier(name, quoted=None):
4496    """Builds an identifier.
4497
4498    Args:
4499        name: The name to turn into an identifier.
4500        quoted: Whether or not force quote the identifier.
4501
4502    Returns:
4503        The identifier ast node.
4504    """
4505
4506    if name is None:
4507        return None
4508
4509    if isinstance(name, Identifier):
4510        identifier = name
4511    elif isinstance(name, str):
4512        identifier = Identifier(
4513            this=name,
4514            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
4515        )
4516    else:
4517        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
4518    return identifier
4519
4520
4521INTERVAL_STRING_RE = re.compile(r"\s*([0-9]+)\s*([a-zA-Z]+)\s*")
4522
4523
4524def to_interval(interval: str | Literal) -> Interval:
4525    """Builds an interval expression from a string like '1 day' or '5 months'."""
4526    if isinstance(interval, Literal):
4527        if not interval.is_string:
4528            raise ValueError("Invalid interval string.")
4529
4530        interval = interval.this
4531
4532    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
4533
4534    if not interval_parts:
4535        raise ValueError("Invalid interval string.")
4536
4537    return Interval(
4538        this=Literal.string(interval_parts.group(1)),
4539        unit=Var(this=interval_parts.group(2)),
4540    )
4541
4542
4543@t.overload
4544def to_table(sql_path: str | Table, **kwargs) -> Table:
4545    ...
4546
4547
4548@t.overload
4549def to_table(sql_path: None, **kwargs) -> None:
4550    ...
4551
4552
4553def to_table(sql_path: t.Optional[str | Table], **kwargs) -> t.Optional[Table]:
4554    """
4555    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
4556    If a table is passed in then that table is returned.
4557
4558    Args:
4559        sql_path: a `[catalog].[schema].[table]` string.
4560
4561    Returns:
4562        A table expression.
4563    """
4564    if sql_path is None or isinstance(sql_path, Table):
4565        return sql_path
4566    if not isinstance(sql_path, str):
4567        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
4568
4569    catalog, db, table_name = (to_identifier(x) for x in split_num_words(sql_path, ".", 3))
4570    return Table(this=table_name, db=db, catalog=catalog, **kwargs)
4571
4572
4573def to_column(sql_path: str | Column, **kwargs) -> Column:
4574    """
4575    Create a column from a `[table].[column]` sql path. Schema is optional.
4576
4577    If a column is passed in then that column is returned.
4578
4579    Args:
4580        sql_path: `[table].[column]` string
4581    Returns:
4582        Table: A column expression
4583    """
4584    if sql_path is None or isinstance(sql_path, Column):
4585        return sql_path
4586    if not isinstance(sql_path, str):
4587        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
4588    return column(*reversed(sql_path.split(".")), **kwargs)  # type: ignore
4589
4590
4591def alias_(
4592    expression: ExpOrStr,
4593    alias: str | Identifier,
4594    table: bool | t.Sequence[str | Identifier] = False,
4595    quoted: t.Optional[bool] = None,
4596    dialect: DialectType = None,
4597    **opts,
4598):
4599    """Create an Alias expression.
4600
4601    Example:
4602        >>> alias_('foo', 'bar').sql()
4603        'foo AS bar'
4604
4605        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
4606        '(SELECT 1, 2) AS bar(a, b)'
4607
4608    Args:
4609        expression: the SQL code strings to parse.
4610            If an Expression instance is passed, this is used as-is.
4611        alias: the alias name to use. If the name has
4612            special characters it is quoted.
4613        table: Whether or not to create a table alias, can also be a list of columns.
4614        quoted: whether or not to quote the alias
4615        dialect: the dialect used to parse the input expression.
4616        **opts: other options to use to parse the input expressions.
4617
4618    Returns:
4619        Alias: the aliased expression
4620    """
4621    exp = maybe_parse(expression, dialect=dialect, **opts)
4622    alias = to_identifier(alias, quoted=quoted)
4623
4624    if table:
4625        table_alias = TableAlias(this=alias)
4626        exp.set("alias", table_alias)
4627
4628        if not isinstance(table, bool):
4629            for column in table:
4630                table_alias.append("columns", to_identifier(column, quoted=quoted))
4631
4632        return exp
4633
4634    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
4635    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
4636    # for the complete Window expression.
4637    #
4638    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
4639
4640    if "alias" in exp.arg_types and not isinstance(exp, Window):
4641        exp = exp.copy()
4642        exp.set("alias", alias)
4643        return exp
4644    return Alias(this=exp, alias=alias)
4645
4646
4647def subquery(expression, alias=None, dialect=None, **opts):
4648    """
4649    Build a subquery expression.
4650
4651    Example:
4652        >>> subquery('select x from tbl', 'bar').select('x').sql()
4653        'SELECT x FROM (SELECT x FROM tbl) AS bar'
4654
4655    Args:
4656        expression (str | Expression): the SQL code strings to parse.
4657            If an Expression instance is passed, this is used as-is.
4658        alias (str | Expression): the alias name to use.
4659        dialect (str): the dialect used to parse the input expression.
4660        **opts: other options to use to parse the input expressions.
4661
4662    Returns:
4663        Select: a new select with the subquery expression included
4664    """
4665
4666    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
4667    return Select().from_(expression, dialect=dialect, **opts)
4668
4669
4670def column(
4671    col: str | Identifier,
4672    table: t.Optional[str | Identifier] = None,
4673    db: t.Optional[str | Identifier] = None,
4674    catalog: t.Optional[str | Identifier] = None,
4675    quoted: t.Optional[bool] = None,
4676) -> Column:
4677    """
4678    Build a Column.
4679
4680    Args:
4681        col: column name
4682        table: table name
4683        db: db name
4684        catalog: catalog name
4685        quoted: whether or not to force quote each part
4686    Returns:
4687        Column: column instance
4688    """
4689    return Column(
4690        this=to_identifier(col, quoted=quoted),
4691        table=to_identifier(table, quoted=quoted),
4692        db=to_identifier(db, quoted=quoted),
4693        catalog=to_identifier(catalog, quoted=quoted),
4694    )
4695
4696
4697def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
4698    """Cast an expression to a data type.
4699
4700    Example:
4701        >>> cast('x + 1', 'int').sql()
4702        'CAST(x + 1 AS INT)'
4703
4704    Args:
4705        expression: The expression to cast.
4706        to: The datatype to cast to.
4707
4708    Returns:
4709        A cast node.
4710    """
4711    expression = maybe_parse(expression, **opts)
4712    return Cast(this=expression, to=DataType.build(to, **opts))
4713
4714
4715def table_(table, db=None, catalog=None, quoted=None, alias=None) -> Table:
4716    """Build a Table.
4717
4718    Args:
4719        table (str | Expression): column name
4720        db (str | Expression): db name
4721        catalog (str | Expression): catalog name
4722
4723    Returns:
4724        Table: table instance
4725    """
4726    return Table(
4727        this=to_identifier(table, quoted=quoted),
4728        db=to_identifier(db, quoted=quoted),
4729        catalog=to_identifier(catalog, quoted=quoted),
4730        alias=TableAlias(this=to_identifier(alias)) if alias else None,
4731    )
4732
4733
4734def values(
4735    values: t.Iterable[t.Tuple[t.Any, ...]],
4736    alias: t.Optional[str] = None,
4737    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
4738) -> Values:
4739    """Build VALUES statement.
4740
4741    Example:
4742        >>> values([(1, '2')]).sql()
4743        "VALUES (1, '2')"
4744
4745    Args:
4746        values: values statements that will be converted to SQL
4747        alias: optional alias
4748        columns: Optional list of ordered column names or ordered dictionary of column names to types.
4749         If either are provided then an alias is also required.
4750         If a dictionary is provided then the first column of the values will be casted to the expected type
4751         in order to help with type inference.
4752
4753    Returns:
4754        Values: the Values expression object
4755    """
4756    if columns and not alias:
4757        raise ValueError("Alias is required when providing columns")
4758    table_alias = (
4759        TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
4760        if columns
4761        else TableAlias(this=to_identifier(alias) if alias else None)
4762    )
4763    expressions = [convert(tup) for tup in values]
4764    if columns and isinstance(columns, dict):
4765        types = list(columns.values())
4766        expressions[0].set(
4767            "expressions",
4768            [cast(x, types[i]) for i, x in enumerate(expressions[0].expressions)],
4769        )
4770    return Values(
4771        expressions=expressions,
4772        alias=table_alias,
4773    )
4774
4775
4776def var(name: t.Optional[ExpOrStr]) -> Var:
4777    """Build a SQL variable.
4778
4779    Example:
4780        >>> repr(var('x'))
4781        '(VAR this: x)'
4782
4783        >>> repr(var(column('x', table='y')))
4784        '(VAR this: x)'
4785
4786    Args:
4787        name: The name of the var or an expression who's name will become the var.
4788
4789    Returns:
4790        The new variable node.
4791    """
4792    if not name:
4793        raise ValueError("Cannot convert empty name into var.")
4794
4795    if isinstance(name, Expression):
4796        name = name.name
4797    return Var(this=name)
4798
4799
4800def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
4801    """Build ALTER TABLE... RENAME... expression
4802
4803    Args:
4804        old_name: The old name of the table
4805        new_name: The new name of the table
4806
4807    Returns:
4808        Alter table expression
4809    """
4810    old_table = to_table(old_name)
4811    new_table = to_table(new_name)
4812    return AlterTable(
4813        this=old_table,
4814        actions=[
4815            RenameTable(this=new_table),
4816        ],
4817    )
4818
4819
4820def convert(value) -> Expression:
4821    """Convert a python value into an expression object.
4822
4823    Raises an error if a conversion is not possible.
4824
4825    Args:
4826        value (Any): a python object
4827
4828    Returns:
4829        Expression: the equivalent expression object
4830    """
4831    if isinstance(value, Expression):
4832        return value
4833    if value is None:
4834        return NULL
4835    if isinstance(value, bool):
4836        return Boolean(this=value)
4837    if isinstance(value, str):
4838        return Literal.string(value)
4839    if isinstance(value, float) and math.isnan(value):
4840        return NULL
4841    if isinstance(value, numbers.Number):
4842        return Literal.number(value)
4843    if isinstance(value, tuple):
4844        return Tuple(expressions=[convert(v) for v in value])
4845    if isinstance(value, list):
4846        return Array(expressions=[convert(v) for v in value])
4847    if isinstance(value, dict):
4848        return Map(
4849            keys=[convert(k) for k in value],
4850            values=[convert(v) for v in value.values()],
4851        )
4852    if isinstance(value, datetime.datetime):
4853        datetime_literal = Literal.string(
4854            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
4855        )
4856        return TimeStrToTime(this=datetime_literal)
4857    if isinstance(value, datetime.date):
4858        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
4859        return DateStrToDate(this=date_literal)
4860    raise ValueError(f"Cannot convert {value}")
4861
4862
4863def replace_children(expression, fun, *args, **kwargs):
4864    """
4865    Replace children of an expression with the result of a lambda fun(child) -> exp.
4866    """
4867    for k, v in expression.args.items():
4868        is_list_arg = type(v) is list
4869
4870        child_nodes = v if is_list_arg else [v]
4871        new_child_nodes = []
4872
4873        for cn in child_nodes:
4874            if isinstance(cn, Expression):
4875                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
4876                    new_child_nodes.append(child_node)
4877                    child_node.parent = expression
4878                    child_node.arg_key = k
4879            else:
4880                new_child_nodes.append(cn)
4881
4882        expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0)
4883
4884
4885def column_table_names(expression):
4886    """
4887    Return all table names referenced through columns in an expression.
4888
4889    Example:
4890        >>> import sqlglot
4891        >>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e"))
4892        ['c', 'a']
4893
4894    Args:
4895        expression (sqlglot.Expression): expression to find table names
4896
4897    Returns:
4898        list: A list of unique names
4899    """
4900    return list(dict.fromkeys(column.table for column in expression.find_all(Column)))
4901
4902
4903def table_name(table) -> str:
4904    """Get the full name of a table as a string.
4905
4906    Args:
4907        table (exp.Table | str): table expression node or string.
4908
4909    Examples:
4910        >>> from sqlglot import exp, parse_one
4911        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
4912        'a.b.c'
4913
4914    Returns:
4915        The table name.
4916    """
4917
4918    table = maybe_parse(table, into=Table)
4919
4920    if not table:
4921        raise ValueError(f"Cannot parse {table}")
4922
4923    return ".".join(
4924        part
4925        for part in (
4926            table.text("catalog"),
4927            table.text("db"),
4928            table.name,
4929        )
4930        if part
4931    )
4932
4933
4934def replace_tables(expression, mapping):
4935    """Replace all tables in expression according to the mapping.
4936
4937    Args:
4938        expression (sqlglot.Expression): expression node to be transformed and replaced.
4939        mapping (Dict[str, str]): mapping of table names.
4940
4941    Examples:
4942        >>> from sqlglot import exp, parse_one
4943        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
4944        'SELECT * FROM c'
4945
4946    Returns:
4947        The mapped expression.
4948    """
4949
4950    def _replace_tables(node):
4951        if isinstance(node, Table):
4952            new_name = mapping.get(table_name(node))
4953            if new_name:
4954                return to_table(
4955                    new_name,
4956                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
4957                )
4958        return node
4959
4960    return expression.transform(_replace_tables)
4961
4962
4963def replace_placeholders(expression, *args, **kwargs):
4964    """Replace placeholders in an expression.
4965
4966    Args:
4967        expression (sqlglot.Expression): expression node to be transformed and replaced.
4968        args: positional names that will substitute unnamed placeholders in the given order.
4969        kwargs: keyword arguments that will substitute named placeholders.
4970
4971    Examples:
4972        >>> from sqlglot import exp, parse_one
4973        >>> replace_placeholders(
4974        ...     parse_one("select * from :tbl where ? = ?"), "a", "b", tbl="foo"
4975        ... ).sql()
4976        'SELECT * FROM foo WHERE a = b'
4977
4978    Returns:
4979        The mapped expression.
4980    """
4981
4982    def _replace_placeholders(node, args, **kwargs):
4983        if isinstance(node, Placeholder):
4984            if node.name:
4985                new_name = kwargs.get(node.name)
4986                if new_name:
4987                    return to_identifier(new_name)
4988            else:
4989                try:
4990                    return to_identifier(next(args))
4991                except StopIteration:
4992                    pass
4993        return node
4994
4995    return expression.transform(_replace_placeholders, iter(args), **kwargs)
4996
4997
4998def expand(expression: Expression, sources: t.Dict[str, Subqueryable], copy=True) -> Expression:
4999    """Transforms an expression by expanding all referenced sources into subqueries.
5000
5001    Examples:
5002        >>> from sqlglot import parse_one
5003        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
5004        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
5005
5006    Args:
5007        expression: The expression to expand.
5008        sources: A dictionary of name to Subqueryables.
5009        copy: Whether or not to copy the expression during transformation. Defaults to True.
5010
5011    Returns:
5012        The transformed expression.
5013    """
5014
5015    def _expand(node: Expression):
5016        if isinstance(node, Table):
5017            name = table_name(node)
5018            source = sources.get(name)
5019            if source:
5020                subquery = source.subquery(node.alias or name)
5021                subquery.comments = [f"source: {name}"]
5022                return subquery
5023        return node
5024
5025    return expression.transform(_expand, copy=copy)
5026
5027
5028def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
5029    """
5030    Returns a Func expression.
5031
5032    Examples:
5033        >>> func("abs", 5).sql()
5034        'ABS(5)'
5035
5036        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
5037        'CAST(5 AS DOUBLE)'
5038
5039    Args:
5040        name: the name of the function to build.
5041        args: the args used to instantiate the function of interest.
5042        dialect: the source dialect.
5043        kwargs: the kwargs used to instantiate the function of interest.
5044
5045    Note:
5046        The arguments `args` and `kwargs` are mutually exclusive.
5047
5048    Returns:
5049        An instance of the function of interest, or an anonymous function, if `name` doesn't
5050        correspond to an existing `sqlglot.expressions.Func` class.
5051    """
5052    if args and kwargs:
5053        raise ValueError("Can't use both args and kwargs to instantiate a function.")
5054
5055    from sqlglot.dialects.dialect import Dialect
5056
5057    converted = [convert(arg) for arg in args]
5058    kwargs = {key: convert(value) for key, value in kwargs.items()}
5059
5060    parser = Dialect.get_or_raise(dialect)().parser()
5061    from_args_list = parser.FUNCTIONS.get(name.upper())
5062
5063    if from_args_list:
5064        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
5065    else:
5066        kwargs = kwargs or {"expressions": converted}
5067        function = Anonymous(this=name, **kwargs)
5068
5069    for error_message in function.error_messages(converted):
5070        raise ValueError(error_message)
5071
5072    return function
5073
5074
5075def true():
5076    """
5077    Returns a true Boolean expression.
5078    """
5079    return Boolean(this=True)
5080
5081
5082def false():
5083    """
5084    Returns a false Boolean expression.
5085    """
5086    return Boolean(this=False)
5087
5088
5089def null():
5090    """
5091    Returns a Null expression.
5092    """
5093    return Null()
5094
5095
5096# TODO: deprecate this
5097TRUE = Boolean(this=True)
5098FALSE = Boolean(this=False)
5099NULL = Null()
class Expression:
 57class Expression(metaclass=_Expression):
 58    """
 59    The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary
 60    context, such as its child expressions, their names (arg keys), and whether a given child expression
 61    is optional or not.
 62
 63    Attributes:
 64        key: a unique key for each class in the Expression hierarchy. This is useful for hashing
 65            and representing expressions as strings.
 66        arg_types: determines what arguments (child nodes) are supported by an expression. It
 67            maps arg keys to booleans that indicate whether the corresponding args are optional.
 68
 69    Example:
 70        >>> class Foo(Expression):
 71        ...     arg_types = {"this": True, "expression": False}
 72
 73        The above definition informs us that Foo is an Expression that requires an argument called
 74        "this" and may also optionally receive an argument called "expression".
 75
 76    Args:
 77        args: a mapping used for retrieving the arguments of an expression, given their arg keys.
 78        parent: a reference to the parent expression (or None, in case of root expressions).
 79        arg_key: the arg key an expression is associated with, i.e. the name its parent expression
 80            uses to refer to it.
 81        comments: a list of comments that are associated with a given expression. This is used in
 82            order to preserve comments when transpiling SQL code.
 83        _type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the
 84            optimizer, in order to enable some transformations that require type information.
 85    """
 86
 87    key = "expression"
 88    arg_types = {"this": True}
 89    __slots__ = ("args", "parent", "arg_key", "comments", "_type", "_meta", "_hash")
 90
 91    def __init__(self, **args: t.Any):
 92        self.args: t.Dict[str, t.Any] = args
 93        self.parent: t.Optional[Expression] = None
 94        self.arg_key: t.Optional[str] = None
 95        self.comments: t.Optional[t.List[str]] = None
 96        self._type: t.Optional[DataType] = None
 97        self._meta: t.Optional[t.Dict[str, t.Any]] = None
 98        self._hash: t.Optional[int] = None
 99
100        for arg_key, value in self.args.items():
101            self._set_parent(arg_key, value)
102
103    def __eq__(self, other) -> bool:
104        return type(self) is type(other) and hash(self) == hash(other)
105
106    @property
107    def hashable_args(self) -> t.Any:
108        args = (self.args.get(k) for k in self.arg_types)
109
110        return tuple(
111            (tuple(_norm_arg(a) for a in arg) if arg else None)
112            if type(arg) is list
113            else (_norm_arg(arg) if arg is not None and arg is not False else None)
114            for arg in args
115        )
116
117    def __hash__(self) -> int:
118        if self._hash is not None:
119            return self._hash
120
121        return hash((self.__class__, self.hashable_args))
122
123    @property
124    def this(self):
125        """
126        Retrieves the argument with key "this".
127        """
128        return self.args.get("this")
129
130    @property
131    def expression(self):
132        """
133        Retrieves the argument with key "expression".
134        """
135        return self.args.get("expression")
136
137    @property
138    def expressions(self):
139        """
140        Retrieves the argument with key "expressions".
141        """
142        return self.args.get("expressions") or []
143
144    def text(self, key) -> str:
145        """
146        Returns a textual representation of the argument corresponding to "key". This can only be used
147        for args that are strings or leaf Expression instances, such as identifiers and literals.
148        """
149        field = self.args.get(key)
150        if isinstance(field, str):
151            return field
152        if isinstance(field, (Identifier, Literal, Var)):
153            return field.this
154        if isinstance(field, (Star, Null)):
155            return field.name
156        return ""
157
158    @property
159    def is_string(self) -> bool:
160        """
161        Checks whether a Literal expression is a string.
162        """
163        return isinstance(self, Literal) and self.args["is_string"]
164
165    @property
166    def is_number(self) -> bool:
167        """
168        Checks whether a Literal expression is a number.
169        """
170        return isinstance(self, Literal) and not self.args["is_string"]
171
172    @property
173    def is_int(self) -> bool:
174        """
175        Checks whether a Literal expression is an integer.
176        """
177        if self.is_number:
178            try:
179                int(self.name)
180                return True
181            except ValueError:
182                pass
183        return False
184
185    @property
186    def is_star(self) -> bool:
187        """Checks whether an expression is a star."""
188        return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star))
189
190    @property
191    def alias(self) -> str:
192        """
193        Returns the alias of the expression, or an empty string if it's not aliased.
194        """
195        if isinstance(self.args.get("alias"), TableAlias):
196            return self.args["alias"].name
197        return self.text("alias")
198
199    @property
200    def name(self) -> str:
201        return self.text("this")
202
203    @property
204    def alias_or_name(self):
205        return self.alias or self.name
206
207    @property
208    def output_name(self):
209        """
210        Name of the output column if this expression is a selection.
211
212        If the Expression has no output name, an empty string is returned.
213
214        Example:
215            >>> from sqlglot import parse_one
216            >>> parse_one("SELECT a").expressions[0].output_name
217            'a'
218            >>> parse_one("SELECT b AS c").expressions[0].output_name
219            'c'
220            >>> parse_one("SELECT 1 + 2").expressions[0].output_name
221            ''
222        """
223        return ""
224
225    @property
226    def type(self) -> t.Optional[DataType]:
227        return self._type
228
229    @type.setter
230    def type(self, dtype: t.Optional[DataType | DataType.Type | str]) -> None:
231        if dtype and not isinstance(dtype, DataType):
232            dtype = DataType.build(dtype)
233        self._type = dtype  # type: ignore
234
235    @property
236    def meta(self) -> t.Dict[str, t.Any]:
237        if self._meta is None:
238            self._meta = {}
239        return self._meta
240
241    def __deepcopy__(self, memo):
242        copy = self.__class__(**deepcopy(self.args))
243        if self.comments is not None:
244            copy.comments = deepcopy(self.comments)
245
246        if self._type is not None:
247            copy._type = self._type.copy()
248
249        if self._meta is not None:
250            copy._meta = deepcopy(self._meta)
251
252        return copy
253
254    def copy(self):
255        """
256        Returns a deep copy of the expression.
257        """
258        new = deepcopy(self)
259        new.parent = self.parent
260        return new
261
262    def append(self, arg_key, value):
263        """
264        Appends value to arg_key if it's a list or sets it as a new list.
265
266        Args:
267            arg_key (str): name of the list expression arg
268            value (Any): value to append to the list
269        """
270        if not isinstance(self.args.get(arg_key), list):
271            self.args[arg_key] = []
272        self.args[arg_key].append(value)
273        self._set_parent(arg_key, value)
274
275    def set(self, arg_key, value):
276        """
277        Sets `arg_key` to `value`.
278
279        Args:
280            arg_key (str): name of the expression arg.
281            value: value to set the arg to.
282        """
283        self.args[arg_key] = value
284        self._set_parent(arg_key, value)
285
286    def _set_parent(self, arg_key, value):
287        if hasattr(value, "parent"):
288            value.parent = self
289            value.arg_key = arg_key
290        elif type(value) is list:
291            for v in value:
292                if hasattr(v, "parent"):
293                    v.parent = self
294                    v.arg_key = arg_key
295
296    @property
297    def depth(self):
298        """
299        Returns the depth of this tree.
300        """
301        if self.parent:
302            return self.parent.depth + 1
303        return 0
304
305    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
306        """Yields the key and expression for all arguments, exploding list args."""
307        for k, vs in self.args.items():
308            if type(vs) is list:
309                for v in vs:
310                    if hasattr(v, "parent"):
311                        yield k, v
312            else:
313                if hasattr(vs, "parent"):
314                    yield k, vs
315
316    def find(self, *expression_types: t.Type[E], bfs=True) -> E | None:
317        """
318        Returns the first node in this tree which matches at least one of
319        the specified types.
320
321        Args:
322            expression_types: the expression type(s) to match.
323
324        Returns:
325            The node which matches the criteria or None if no such node was found.
326        """
327        return next(self.find_all(*expression_types, bfs=bfs), None)
328
329    def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]:
330        """
331        Returns a generator object which visits all nodes in this tree and only
332        yields those that match at least one of the specified expression types.
333
334        Args:
335            expression_types: the expression type(s) to match.
336
337        Returns:
338            The generator object.
339        """
340        for expression, *_ in self.walk(bfs=bfs):
341            if isinstance(expression, expression_types):
342                yield expression
343
344    def find_ancestor(self, *expression_types: t.Type[E]) -> E | None:
345        """
346        Returns a nearest parent matching expression_types.
347
348        Args:
349            expression_types: the expression type(s) to match.
350
351        Returns:
352            The parent node.
353        """
354        ancestor = self.parent
355        while ancestor and not isinstance(ancestor, expression_types):
356            ancestor = ancestor.parent
357        return t.cast(E, ancestor)
358
359    @property
360    def parent_select(self):
361        """
362        Returns the parent select statement.
363        """
364        return self.find_ancestor(Select)
365
366    @property
367    def same_parent(self):
368        """Returns if the parent is the same class as itself."""
369        return type(self.parent) is self.__class__
370
371    def root(self) -> Expression:
372        """
373        Returns the root expression of this tree.
374        """
375        expression = self
376        while expression.parent:
377            expression = expression.parent
378        return expression
379
380    def walk(self, bfs=True, prune=None):
381        """
382        Returns a generator object which visits all nodes in this tree.
383
384        Args:
385            bfs (bool): if set to True the BFS traversal order will be applied,
386                otherwise the DFS traversal will be used instead.
387            prune ((node, parent, arg_key) -> bool): callable that returns True if
388                the generator should stop traversing this branch of the tree.
389
390        Returns:
391            the generator object.
392        """
393        if bfs:
394            yield from self.bfs(prune=prune)
395        else:
396            yield from self.dfs(prune=prune)
397
398    def dfs(self, parent=None, key=None, prune=None):
399        """
400        Returns a generator object which visits all nodes in this tree in
401        the DFS (Depth-first) order.
402
403        Returns:
404            The generator object.
405        """
406        parent = parent or self.parent
407        yield self, parent, key
408        if prune and prune(self, parent, key):
409            return
410
411        for k, v in self.iter_expressions():
412            yield from v.dfs(self, k, prune)
413
414    def bfs(self, prune=None):
415        """
416        Returns a generator object which visits all nodes in this tree in
417        the BFS (Breadth-first) order.
418
419        Returns:
420            The generator object.
421        """
422        queue = deque([(self, self.parent, None)])
423
424        while queue:
425            item, parent, key = queue.popleft()
426
427            yield item, parent, key
428            if prune and prune(item, parent, key):
429                continue
430
431            for k, v in item.iter_expressions():
432                queue.append((v, item, k))
433
434    def unnest(self):
435        """
436        Returns the first non parenthesis child or self.
437        """
438        expression = self
439        while type(expression) is Paren:
440            expression = expression.this
441        return expression
442
443    def unalias(self):
444        """
445        Returns the inner expression if this is an Alias.
446        """
447        if isinstance(self, Alias):
448            return self.this
449        return self
450
451    def unnest_operands(self):
452        """
453        Returns unnested operands as a tuple.
454        """
455        return tuple(arg.unnest() for _, arg in self.iter_expressions())
456
457    def flatten(self, unnest=True):
458        """
459        Returns a generator which yields child nodes who's parents are the same class.
460
461        A AND B AND C -> [A, B, C]
462        """
463        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
464            if not type(node) is self.__class__:
465                yield node.unnest() if unnest else node
466
467    def __str__(self):
468        return self.sql()
469
470    def __repr__(self):
471        return self._to_s()
472
473    def sql(self, dialect: DialectType = None, **opts) -> str:
474        """
475        Returns SQL string representation of this tree.
476
477        Args:
478            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
479            opts: other `sqlglot.generator.Generator` options.
480
481        Returns:
482            The SQL string.
483        """
484        from sqlglot.dialects import Dialect
485
486        return Dialect.get_or_raise(dialect)().generate(self, **opts)
487
488    def _to_s(self, hide_missing: bool = True, level: int = 0) -> str:
489        indent = "" if not level else "\n"
490        indent += "".join(["  "] * level)
491        left = f"({self.key.upper()} "
492
493        args: t.Dict[str, t.Any] = {
494            k: ", ".join(
495                v._to_s(hide_missing=hide_missing, level=level + 1)
496                if hasattr(v, "_to_s")
497                else str(v)
498                for v in ensure_list(vs)
499                if v is not None
500            )
501            for k, vs in self.args.items()
502        }
503        args["comments"] = self.comments
504        args["type"] = self.type
505        args = {k: v for k, v in args.items() if v or not hide_missing}
506
507        right = ", ".join(f"{k}: {v}" for k, v in args.items())
508        right += ")"
509
510        return indent + left + right
511
512    def transform(self, fun, *args, copy=True, **kwargs):
513        """
514        Recursively visits all tree nodes (excluding already transformed ones)
515        and applies the given transformation function to each node.
516
517        Args:
518            fun (function): a function which takes a node as an argument and returns a
519                new transformed node or the same node without modifications. If the function
520                returns None, then the corresponding node will be removed from the syntax tree.
521            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
522                modified in place.
523
524        Returns:
525            The transformed tree.
526        """
527        node = self.copy() if copy else self
528        new_node = fun(node, *args, **kwargs)
529
530        if new_node is None or not isinstance(new_node, Expression):
531            return new_node
532        if new_node is not node:
533            new_node.parent = node.parent
534            return new_node
535
536        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
537        return new_node
538
539    def replace(self, expression):
540        """
541        Swap out this expression with a new expression.
542
543        For example::
544
545            >>> tree = Select().select("x").from_("tbl")
546            >>> tree.find(Column).replace(Column(this="y"))
547            (COLUMN this: y)
548            >>> tree.sql()
549            'SELECT y FROM tbl'
550
551        Args:
552            expression (Expression|None): new node
553
554        Returns:
555            The new expression or expressions.
556        """
557        if not self.parent:
558            return expression
559
560        parent = self.parent
561        self.parent = None
562
563        replace_children(parent, lambda child: expression if child is self else child)
564        return expression
565
566    def pop(self):
567        """
568        Remove this expression from its AST.
569
570        Returns:
571            The popped expression.
572        """
573        self.replace(None)
574        return self
575
576    def assert_is(self, type_):
577        """
578        Assert that this `Expression` is an instance of `type_`.
579
580        If it is NOT an instance of `type_`, this raises an assertion error.
581        Otherwise, this returns this expression.
582
583        Examples:
584            This is useful for type security in chained expressions:
585
586            >>> import sqlglot
587            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
588            'SELECT x, z FROM y'
589        """
590        assert isinstance(self, type_)
591        return self
592
593    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
594        """
595        Checks if this expression is valid (e.g. all mandatory args are set).
596
597        Args:
598            args: a sequence of values that were used to instantiate a Func expression. This is used
599                to check that the provided arguments don't exceed the function argument limit.
600
601        Returns:
602            A list of error messages for all possible errors that were found.
603        """
604        errors: t.List[str] = []
605
606        for k in self.args:
607            if k not in self.arg_types:
608                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
609        for k, mandatory in self.arg_types.items():
610            v = self.args.get(k)
611            if mandatory and (v is None or (isinstance(v, list) and not v)):
612                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
613
614        if (
615            args
616            and isinstance(self, Func)
617            and len(args) > len(self.arg_types)
618            and not self.is_var_len_args
619        ):
620            errors.append(
621                f"The number of provided arguments ({len(args)}) is greater than "
622                f"the maximum number of supported arguments ({len(self.arg_types)})"
623            )
624
625        return errors
626
627    def dump(self):
628        """
629        Dump this Expression to a JSON-serializable dict.
630        """
631        from sqlglot.serde import dump
632
633        return dump(self)
634
635    @classmethod
636    def load(cls, obj):
637        """
638        Load a dict (as returned by `Expression.dump`) into an Expression instance.
639        """
640        from sqlglot.serde import load
641
642        return load(obj)

The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary context, such as its child expressions, their names (arg keys), and whether a given child expression is optional or not.

Attributes:
  • key: a unique key for each class in the Expression hierarchy. This is useful for hashing and representing expressions as strings.
  • arg_types: determines what arguments (child nodes) are supported by an expression. It maps arg keys to booleans that indicate whether the corresponding args are optional.
Example:
>>> class Foo(Expression):
...     arg_types = {"this": True, "expression": False}

The above definition informs us that Foo is an Expression that requires an argument called "this" and may also optionally receive an argument called "expression".

Arguments:
  • args: a mapping used for retrieving the arguments of an expression, given their arg keys.
  • parent: a reference to the parent expression (or None, in case of root expressions).
  • arg_key: the arg key an expression is associated with, i.e. the name its parent expression uses to refer to it.
  • comments: a list of comments that are associated with a given expression. This is used in order to preserve comments when transpiling SQL code.
  • _type: the sqlglot.expressions.DataType type of an expression. This is inferred by the optimizer, in order to enable some transformations that require type information.
Expression(**args: Any)
 91    def __init__(self, **args: t.Any):
 92        self.args: t.Dict[str, t.Any] = args
 93        self.parent: t.Optional[Expression] = None
 94        self.arg_key: t.Optional[str] = None
 95        self.comments: t.Optional[t.List[str]] = None
 96        self._type: t.Optional[DataType] = None
 97        self._meta: t.Optional[t.Dict[str, t.Any]] = None
 98        self._hash: t.Optional[int] = None
 99
100        for arg_key, value in self.args.items():
101            self._set_parent(arg_key, value)
this

Retrieves the argument with key "this".

expression

Retrieves the argument with key "expression".

expressions

Retrieves the argument with key "expressions".

def text(self, key) -> str:
144    def text(self, key) -> str:
145        """
146        Returns a textual representation of the argument corresponding to "key". This can only be used
147        for args that are strings or leaf Expression instances, such as identifiers and literals.
148        """
149        field = self.args.get(key)
150        if isinstance(field, str):
151            return field
152        if isinstance(field, (Identifier, Literal, Var)):
153            return field.this
154        if isinstance(field, (Star, Null)):
155            return field.name
156        return ""

Returns a textual representation of the argument corresponding to "key". This can only be used for args that are strings or leaf Expression instances, such as identifiers and literals.

is_string: bool

Checks whether a Literal expression is a string.

is_number: bool

Checks whether a Literal expression is a number.

is_int: bool

Checks whether a Literal expression is an integer.

is_star: bool

Checks whether an expression is a star.

alias: str

Returns the alias of the expression, or an empty string if it's not aliased.

output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
def copy(self):
254    def copy(self):
255        """
256        Returns a deep copy of the expression.
257        """
258        new = deepcopy(self)
259        new.parent = self.parent
260        return new

Returns a deep copy of the expression.

def append(self, arg_key, value):
262    def append(self, arg_key, value):
263        """
264        Appends value to arg_key if it's a list or sets it as a new list.
265
266        Args:
267            arg_key (str): name of the list expression arg
268            value (Any): value to append to the list
269        """
270        if not isinstance(self.args.get(arg_key), list):
271            self.args[arg_key] = []
272        self.args[arg_key].append(value)
273        self._set_parent(arg_key, value)

Appends value to arg_key if it's a list or sets it as a new list.

Arguments:
  • arg_key (str): name of the list expression arg
  • value (Any): value to append to the list
def set(self, arg_key, value):
275    def set(self, arg_key, value):
276        """
277        Sets `arg_key` to `value`.
278
279        Args:
280            arg_key (str): name of the expression arg.
281            value: value to set the arg to.
282        """
283        self.args[arg_key] = value
284        self._set_parent(arg_key, value)

Sets arg_key to value.

Arguments:
  • arg_key (str): name of the expression arg.
  • value: value to set the arg to.
depth

Returns the depth of this tree.

def iter_expressions(self) -> Iterator[Tuple[str, sqlglot.expressions.Expression]]:
305    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
306        """Yields the key and expression for all arguments, exploding list args."""
307        for k, vs in self.args.items():
308            if type(vs) is list:
309                for v in vs:
310                    if hasattr(v, "parent"):
311                        yield k, v
312            else:
313                if hasattr(vs, "parent"):
314                    yield k, vs

Yields the key and expression for all arguments, exploding list args.

def find(self, *expression_types: Type[~E], bfs=True) -> Optional[~E]:
316    def find(self, *expression_types: t.Type[E], bfs=True) -> E | None:
317        """
318        Returns the first node in this tree which matches at least one of
319        the specified types.
320
321        Args:
322            expression_types: the expression type(s) to match.
323
324        Returns:
325            The node which matches the criteria or None if no such node was found.
326        """
327        return next(self.find_all(*expression_types, bfs=bfs), None)

Returns the first node in this tree which matches at least one of the specified types.

Arguments:
  • expression_types: the expression type(s) to match.
Returns:

The node which matches the criteria or None if no such node was found.

def find_all(self, *expression_types: Type[~E], bfs=True) -> Iterator[~E]:
329    def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]:
330        """
331        Returns a generator object which visits all nodes in this tree and only
332        yields those that match at least one of the specified expression types.
333
334        Args:
335            expression_types: the expression type(s) to match.
336
337        Returns:
338            The generator object.
339        """
340        for expression, *_ in self.walk(bfs=bfs):
341            if isinstance(expression, expression_types):
342                yield expression

Returns a generator object which visits all nodes in this tree and only yields those that match at least one of the specified expression types.

Arguments:
  • expression_types: the expression type(s) to match.
Returns:

The generator object.

def find_ancestor(self, *expression_types: Type[~E]) -> Optional[~E]:
344    def find_ancestor(self, *expression_types: t.Type[E]) -> E | None:
345        """
346        Returns a nearest parent matching expression_types.
347
348        Args:
349            expression_types: the expression type(s) to match.
350
351        Returns:
352            The parent node.
353        """
354        ancestor = self.parent
355        while ancestor and not isinstance(ancestor, expression_types):
356            ancestor = ancestor.parent
357        return t.cast(E, ancestor)

Returns a nearest parent matching expression_types.

Arguments:
  • expression_types: the expression type(s) to match.
Returns:

The parent node.

parent_select

Returns the parent select statement.

same_parent

Returns if the parent is the same class as itself.

def root(self) -> sqlglot.expressions.Expression:
371    def root(self) -> Expression:
372        """
373        Returns the root expression of this tree.
374        """
375        expression = self
376        while expression.parent:
377            expression = expression.parent
378        return expression

Returns the root expression of this tree.

def walk(self, bfs=True, prune=None):
380    def walk(self, bfs=True, prune=None):
381        """
382        Returns a generator object which visits all nodes in this tree.
383
384        Args:
385            bfs (bool): if set to True the BFS traversal order will be applied,
386                otherwise the DFS traversal will be used instead.
387            prune ((node, parent, arg_key) -> bool): callable that returns True if
388                the generator should stop traversing this branch of the tree.
389
390        Returns:
391            the generator object.
392        """
393        if bfs:
394            yield from self.bfs(prune=prune)
395        else:
396            yield from self.dfs(prune=prune)

Returns a generator object which visits all nodes in this tree.

Arguments:
  • bfs (bool): if set to True the BFS traversal order will be applied, otherwise the DFS traversal will be used instead.
  • prune ((node, parent, arg_key) -> bool): callable that returns True if the generator should stop traversing this branch of the tree.
Returns:

the generator object.

def dfs(self, parent=None, key=None, prune=None):
398    def dfs(self, parent=None, key=None, prune=None):
399        """
400        Returns a generator object which visits all nodes in this tree in
401        the DFS (Depth-first) order.
402
403        Returns:
404            The generator object.
405        """
406        parent = parent or self.parent
407        yield self, parent, key
408        if prune and prune(self, parent, key):
409            return
410
411        for k, v in self.iter_expressions():
412            yield from v.dfs(self, k, prune)

Returns a generator object which visits all nodes in this tree in the DFS (Depth-first) order.

Returns:

The generator object.

def bfs(self, prune=None):
414    def bfs(self, prune=None):
415        """
416        Returns a generator object which visits all nodes in this tree in
417        the BFS (Breadth-first) order.
418
419        Returns:
420            The generator object.
421        """
422        queue = deque([(self, self.parent, None)])
423
424        while queue:
425            item, parent, key = queue.popleft()
426
427            yield item, parent, key
428            if prune and prune(item, parent, key):
429                continue
430
431            for k, v in item.iter_expressions():
432                queue.append((v, item, k))

Returns a generator object which visits all nodes in this tree in the BFS (Breadth-first) order.

Returns:

The generator object.

def unnest(self):
434    def unnest(self):
435        """
436        Returns the first non parenthesis child or self.
437        """
438        expression = self
439        while type(expression) is Paren:
440            expression = expression.this
441        return expression

Returns the first non parenthesis child or self.

def unalias(self):
443    def unalias(self):
444        """
445        Returns the inner expression if this is an Alias.
446        """
447        if isinstance(self, Alias):
448            return self.this
449        return self

Returns the inner expression if this is an Alias.

def unnest_operands(self):
451    def unnest_operands(self):
452        """
453        Returns unnested operands as a tuple.
454        """
455        return tuple(arg.unnest() for _, arg in self.iter_expressions())

Returns unnested operands as a tuple.

def flatten(self, unnest=True):
457    def flatten(self, unnest=True):
458        """
459        Returns a generator which yields child nodes who's parents are the same class.
460
461        A AND B AND C -> [A, B, C]
462        """
463        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
464            if not type(node) is self.__class__:
465                yield node.unnest() if unnest else node

Returns a generator which yields child nodes who's parents are the same class.

A AND B AND C -> [A, B, C]

def sql( self, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> str:
473    def sql(self, dialect: DialectType = None, **opts) -> str:
474        """
475        Returns SQL string representation of this tree.
476
477        Args:
478            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
479            opts: other `sqlglot.generator.Generator` options.
480
481        Returns:
482            The SQL string.
483        """
484        from sqlglot.dialects import Dialect
485
486        return Dialect.get_or_raise(dialect)().generate(self, **opts)

Returns SQL string representation of this tree.

Arguments:
  • dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
  • opts: other sqlglot.generator.Generator options.
Returns:

The SQL string.

def transform(self, fun, *args, copy=True, **kwargs):
512    def transform(self, fun, *args, copy=True, **kwargs):
513        """
514        Recursively visits all tree nodes (excluding already transformed ones)
515        and applies the given transformation function to each node.
516
517        Args:
518            fun (function): a function which takes a node as an argument and returns a
519                new transformed node or the same node without modifications. If the function
520                returns None, then the corresponding node will be removed from the syntax tree.
521            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
522                modified in place.
523
524        Returns:
525            The transformed tree.
526        """
527        node = self.copy() if copy else self
528        new_node = fun(node, *args, **kwargs)
529
530        if new_node is None or not isinstance(new_node, Expression):
531            return new_node
532        if new_node is not node:
533            new_node.parent = node.parent
534            return new_node
535
536        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
537        return new_node

Recursively visits all tree nodes (excluding already transformed ones) and applies the given transformation function to each node.

Arguments:
  • fun (function): a function which takes a node as an argument and returns a new transformed node or the same node without modifications. If the function returns None, then the corresponding node will be removed from the syntax tree.
  • copy (bool): if set to True a new tree instance is constructed, otherwise the tree is modified in place.
Returns:

The transformed tree.

def replace(self, expression):
539    def replace(self, expression):
540        """
541        Swap out this expression with a new expression.
542
543        For example::
544
545            >>> tree = Select().select("x").from_("tbl")
546            >>> tree.find(Column).replace(Column(this="y"))
547            (COLUMN this: y)
548            >>> tree.sql()
549            'SELECT y FROM tbl'
550
551        Args:
552            expression (Expression|None): new node
553
554        Returns:
555            The new expression or expressions.
556        """
557        if not self.parent:
558            return expression
559
560        parent = self.parent
561        self.parent = None
562
563        replace_children(parent, lambda child: expression if child is self else child)
564        return expression

Swap out this expression with a new expression.

For example::

>>> tree = Select().select("x").from_("tbl")
>>> tree.find(Column).replace(Column(this="y"))
(COLUMN this: y)
>>> tree.sql()
'SELECT y FROM tbl'
Arguments:
  • expression (Expression|None): new node
Returns:

The new expression or expressions.

def pop(self):
566    def pop(self):
567        """
568        Remove this expression from its AST.
569
570        Returns:
571            The popped expression.
572        """
573        self.replace(None)
574        return self

Remove this expression from its AST.

Returns:

The popped expression.

def assert_is(self, type_):
576    def assert_is(self, type_):
577        """
578        Assert that this `Expression` is an instance of `type_`.
579
580        If it is NOT an instance of `type_`, this raises an assertion error.
581        Otherwise, this returns this expression.
582
583        Examples:
584            This is useful for type security in chained expressions:
585
586            >>> import sqlglot
587            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
588            'SELECT x, z FROM y'
589        """
590        assert isinstance(self, type_)
591        return self

Assert that this Expression is an instance of type_.

If it is NOT an instance of type_, this raises an assertion error. Otherwise, this returns this expression.

Examples:

This is useful for type security in chained expressions:

>>> import sqlglot
>>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
'SELECT x, z FROM y'
def error_messages(self, args: Optional[Sequence] = None) -> List[str]:
593    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
594        """
595        Checks if this expression is valid (e.g. all mandatory args are set).
596
597        Args:
598            args: a sequence of values that were used to instantiate a Func expression. This is used
599                to check that the provided arguments don't exceed the function argument limit.
600
601        Returns:
602            A list of error messages for all possible errors that were found.
603        """
604        errors: t.List[str] = []
605
606        for k in self.args:
607            if k not in self.arg_types:
608                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
609        for k, mandatory in self.arg_types.items():
610            v = self.args.get(k)
611            if mandatory and (v is None or (isinstance(v, list) and not v)):
612                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
613
614        if (
615            args
616            and isinstance(self, Func)
617            and len(args) > len(self.arg_types)
618            and not self.is_var_len_args
619        ):
620            errors.append(
621                f"The number of provided arguments ({len(args)}) is greater than "
622                f"the maximum number of supported arguments ({len(self.arg_types)})"
623            )
624
625        return errors

Checks if this expression is valid (e.g. all mandatory args are set).

Arguments:
  • args: a sequence of values that were used to instantiate a Func expression. This is used to check that the provided arguments don't exceed the function argument limit.
Returns:

A list of error messages for all possible errors that were found.

def dump(self):
627    def dump(self):
628        """
629        Dump this Expression to a JSON-serializable dict.
630        """
631        from sqlglot.serde import dump
632
633        return dump(self)

Dump this Expression to a JSON-serializable dict.

@classmethod
def load(cls, obj):
635    @classmethod
636    def load(cls, obj):
637        """
638        Load a dict (as returned by `Expression.dump`) into an Expression instance.
639        """
640        from sqlglot.serde import load
641
642        return load(obj)

Load a dict (as returned by Expression.dump) into an Expression instance.

class Condition(Expression):
653class Condition(Expression):
654    def and_(self, *expressions, dialect=None, **opts):
655        """
656        AND this condition with one or multiple expressions.
657
658        Example:
659            >>> condition("x=1").and_("y=1").sql()
660            'x = 1 AND y = 1'
661
662        Args:
663            *expressions (str | Expression): the SQL code strings to parse.
664                If an `Expression` instance is passed, it will be used as-is.
665            dialect (str): the dialect used to parse the input expression.
666            opts (kwargs): other options to use to parse the input expressions.
667
668        Returns:
669            And: the new condition.
670        """
671        return and_(self, *expressions, dialect=dialect, **opts)
672
673    def or_(self, *expressions, dialect=None, **opts):
674        """
675        OR this condition with one or multiple expressions.
676
677        Example:
678            >>> condition("x=1").or_("y=1").sql()
679            'x = 1 OR y = 1'
680
681        Args:
682            *expressions (str | Expression): the SQL code strings to parse.
683                If an `Expression` instance is passed, it will be used as-is.
684            dialect (str): the dialect used to parse the input expression.
685            opts (kwargs): other options to use to parse the input expressions.
686
687        Returns:
688            Or: the new condition.
689        """
690        return or_(self, *expressions, dialect=dialect, **opts)
691
692    def not_(self):
693        """
694        Wrap this condition with NOT.
695
696        Example:
697            >>> condition("x=1").not_().sql()
698            'NOT x = 1'
699
700        Returns:
701            Not: the new condition.
702        """
703        return not_(self)
def and_(self, *expressions, dialect=None, **opts):
654    def and_(self, *expressions, dialect=None, **opts):
655        """
656        AND this condition with one or multiple expressions.
657
658        Example:
659            >>> condition("x=1").and_("y=1").sql()
660            'x = 1 AND y = 1'
661
662        Args:
663            *expressions (str | Expression): the SQL code strings to parse.
664                If an `Expression` instance is passed, it will be used as-is.
665            dialect (str): the dialect used to parse the input expression.
666            opts (kwargs): other options to use to parse the input expressions.
667
668        Returns:
669            And: the new condition.
670        """
671        return and_(self, *expressions, dialect=dialect, **opts)

AND this condition with one or multiple expressions.

Example:
>>> condition("x=1").and_("y=1").sql()
'x = 1 AND y = 1'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

And: the new condition.

def or_(self, *expressions, dialect=None, **opts):
673    def or_(self, *expressions, dialect=None, **opts):
674        """
675        OR this condition with one or multiple expressions.
676
677        Example:
678            >>> condition("x=1").or_("y=1").sql()
679            'x = 1 OR y = 1'
680
681        Args:
682            *expressions (str | Expression): the SQL code strings to parse.
683                If an `Expression` instance is passed, it will be used as-is.
684            dialect (str): the dialect used to parse the input expression.
685            opts (kwargs): other options to use to parse the input expressions.
686
687        Returns:
688            Or: the new condition.
689        """
690        return or_(self, *expressions, dialect=dialect, **opts)

OR this condition with one or multiple expressions.

Example:
>>> condition("x=1").or_("y=1").sql()
'x = 1 OR y = 1'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Or: the new condition.

def not_(self):
692    def not_(self):
693        """
694        Wrap this condition with NOT.
695
696        Example:
697            >>> condition("x=1").not_().sql()
698            'NOT x = 1'
699
700        Returns:
701            Not: the new condition.
702        """
703        return not_(self)

Wrap this condition with NOT.

Example:
>>> condition("x=1").not_().sql()
'NOT x = 1'
Returns:

Not: the new condition.

class Predicate(Condition):
706class Predicate(Condition):
707    """Relationships like x = y, x > 1, x >= y."""

Relationships like x = y, x > 1, x >= y.

class DerivedTable(Expression):
710class DerivedTable(Expression):
711    @property
712    def alias_column_names(self):
713        table_alias = self.args.get("alias")
714        if not table_alias:
715            return []
716        column_list = table_alias.assert_is(TableAlias).args.get("columns") or []
717        return [c.name for c in column_list]
718
719    @property
720    def selects(self):
721        alias = self.args.get("alias")
722
723        if alias:
724            return alias.columns
725        return []
726
727    @property
728    def named_selects(self):
729        return [select.output_name for select in self.selects]
class Unionable(Expression):
732class Unionable(Expression):
733    def union(self, expression, distinct=True, dialect=None, **opts):
734        """
735        Builds a UNION expression.
736
737        Example:
738            >>> import sqlglot
739            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
740            'SELECT * FROM foo UNION SELECT * FROM bla'
741
742        Args:
743            expression (str | Expression): the SQL code string.
744                If an `Expression` instance is passed, it will be used as-is.
745            distinct (bool): set the DISTINCT flag if and only if this is true.
746            dialect (str): the dialect used to parse the input expression.
747            opts (kwargs): other options to use to parse the input expressions.
748        Returns:
749            Union: the Union expression.
750        """
751        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
752
753    def intersect(self, expression, distinct=True, dialect=None, **opts):
754        """
755        Builds an INTERSECT expression.
756
757        Example:
758            >>> import sqlglot
759            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
760            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
761
762        Args:
763            expression (str | Expression): the SQL code string.
764                If an `Expression` instance is passed, it will be used as-is.
765            distinct (bool): set the DISTINCT flag if and only if this is true.
766            dialect (str): the dialect used to parse the input expression.
767            opts (kwargs): other options to use to parse the input expressions.
768        Returns:
769            Intersect: the Intersect expression
770        """
771        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
772
773    def except_(self, expression, distinct=True, dialect=None, **opts):
774        """
775        Builds an EXCEPT expression.
776
777        Example:
778            >>> import sqlglot
779            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
780            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
781
782        Args:
783            expression (str | Expression): the SQL code string.
784                If an `Expression` instance is passed, it will be used as-is.
785            distinct (bool): set the DISTINCT flag if and only if this is true.
786            dialect (str): the dialect used to parse the input expression.
787            opts (kwargs): other options to use to parse the input expressions.
788        Returns:
789            Except: the Except expression
790        """
791        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
def union(self, expression, distinct=True, dialect=None, **opts):
733    def union(self, expression, distinct=True, dialect=None, **opts):
734        """
735        Builds a UNION expression.
736
737        Example:
738            >>> import sqlglot
739            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
740            'SELECT * FROM foo UNION SELECT * FROM bla'
741
742        Args:
743            expression (str | Expression): the SQL code string.
744                If an `Expression` instance is passed, it will be used as-is.
745            distinct (bool): set the DISTINCT flag if and only if this is true.
746            dialect (str): the dialect used to parse the input expression.
747            opts (kwargs): other options to use to parse the input expressions.
748        Returns:
749            Union: the Union expression.
750        """
751        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds a UNION expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
'SELECT * FROM foo UNION SELECT * FROM bla'
Arguments:
  • expression (str | Expression): the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Union: the Union expression.

def intersect(self, expression, distinct=True, dialect=None, **opts):
753    def intersect(self, expression, distinct=True, dialect=None, **opts):
754        """
755        Builds an INTERSECT expression.
756
757        Example:
758            >>> import sqlglot
759            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
760            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
761
762        Args:
763            expression (str | Expression): the SQL code string.
764                If an `Expression` instance is passed, it will be used as-is.
765            distinct (bool): set the DISTINCT flag if and only if this is true.
766            dialect (str): the dialect used to parse the input expression.
767            opts (kwargs): other options to use to parse the input expressions.
768        Returns:
769            Intersect: the Intersect expression
770        """
771        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds an INTERSECT expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Arguments:
  • expression (str | Expression): the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Intersect: the Intersect expression

def except_(self, expression, distinct=True, dialect=None, **opts):
773    def except_(self, expression, distinct=True, dialect=None, **opts):
774        """
775        Builds an EXCEPT expression.
776
777        Example:
778            >>> import sqlglot
779            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
780            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
781
782        Args:
783            expression (str | Expression): the SQL code string.
784                If an `Expression` instance is passed, it will be used as-is.
785            distinct (bool): set the DISTINCT flag if and only if this is true.
786            dialect (str): the dialect used to parse the input expression.
787            opts (kwargs): other options to use to parse the input expressions.
788        Returns:
789            Except: the Except expression
790        """
791        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds an EXCEPT expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Arguments:
  • expression (str | Expression): the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Except: the Except expression

class UDTF(DerivedTable, Unionable):
794class UDTF(DerivedTable, Unionable):
795    pass
class Cache(Expression):
798class Cache(Expression):
799    arg_types = {
800        "with": False,
801        "this": True,
802        "lazy": False,
803        "options": False,
804        "expression": False,
805    }
class Uncache(Expression):
808class Uncache(Expression):
809    arg_types = {"this": True, "exists": False}
class Create(Expression):
812class Create(Expression):
813    arg_types = {
814        "with": False,
815        "this": True,
816        "kind": True,
817        "expression": False,
818        "exists": False,
819        "properties": False,
820        "replace": False,
821        "unique": False,
822        "volatile": False,
823        "indexes": False,
824        "no_schema_binding": False,
825        "begin": False,
826    }
class Describe(Expression):
829class Describe(Expression):
830    arg_types = {"this": True, "kind": False}
class Pragma(Expression):
833class Pragma(Expression):
834    pass
class Set(Expression):
837class Set(Expression):
838    arg_types = {"expressions": False}
class SetItem(Expression):
841class SetItem(Expression):
842    arg_types = {
843        "this": False,
844        "expressions": False,
845        "kind": False,
846        "collate": False,  # MySQL SET NAMES statement
847        "global": False,
848    }
class Show(Expression):
851class Show(Expression):
852    arg_types = {
853        "this": True,
854        "target": False,
855        "offset": False,
856        "limit": False,
857        "like": False,
858        "where": False,
859        "db": False,
860        "full": False,
861        "mutex": False,
862        "query": False,
863        "channel": False,
864        "global": False,
865        "log": False,
866        "position": False,
867        "types": False,
868    }
class UserDefinedFunction(Expression):
871class UserDefinedFunction(Expression):
872    arg_types = {"this": True, "expressions": False, "wrapped": False}
class CharacterSet(Expression):
875class CharacterSet(Expression):
876    arg_types = {"this": True, "default": False}
class With(Expression):
879class With(Expression):
880    arg_types = {"expressions": True, "recursive": False}
881
882    @property
883    def recursive(self) -> bool:
884        return bool(self.args.get("recursive"))
class WithinGroup(Expression):
887class WithinGroup(Expression):
888    arg_types = {"this": True, "expression": False}
class CTE(DerivedTable):
891class CTE(DerivedTable):
892    arg_types = {"this": True, "alias": True}
class TableAlias(Expression):
895class TableAlias(Expression):
896    arg_types = {"this": False, "columns": False}
897
898    @property
899    def columns(self):
900        return self.args.get("columns") or []
class BitString(Condition):
903class BitString(Condition):
904    pass
class HexString(Condition):
907class HexString(Condition):
908    pass
class ByteString(Condition):
911class ByteString(Condition):
912    pass
class Column(Condition):
915class Column(Condition):
916    arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False}
917
918    @property
919    def table(self) -> str:
920        return self.text("table")
921
922    @property
923    def db(self) -> str:
924        return self.text("db")
925
926    @property
927    def catalog(self) -> str:
928        return self.text("catalog")
929
930    @property
931    def output_name(self) -> str:
932        return self.name
933
934    @property
935    def parts(self) -> t.List[Identifier]:
936        """Return the parts of a column in order catalog, db, table, name."""
937        return [part for part in reversed(list(self.args.values())) if part]
938
939    def to_dot(self) -> Dot:
940        """Converts the column into a dot expression."""
941        parts = self.parts
942        parent = self.parent
943
944        while parent:
945            if isinstance(parent, Dot):
946                parts.append(parent.expression)
947            parent = parent.parent
948
949        return Dot.build(parts)
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''

Return the parts of a column in order catalog, db, table, name.

def to_dot(self) -> sqlglot.expressions.Dot:
939    def to_dot(self) -> Dot:
940        """Converts the column into a dot expression."""
941        parts = self.parts
942        parent = self.parent
943
944        while parent:
945            if isinstance(parent, Dot):
946                parts.append(parent.expression)
947            parent = parent.parent
948
949        return Dot.build(parts)

Converts the column into a dot expression.

class ColumnDef(Expression):
952class ColumnDef(Expression):
953    arg_types = {
954        "this": True,
955        "kind": False,
956        "constraints": False,
957        "exists": False,
958    }
class AlterColumn(Expression):
961class AlterColumn(Expression):
962    arg_types = {
963        "this": True,
964        "dtype": False,
965        "collate": False,
966        "using": False,
967        "default": False,
968        "drop": False,
969    }
class RenameTable(Expression):
972class RenameTable(Expression):
973    pass
class SetTag(Expression):
976class SetTag(Expression):
977    arg_types = {"expressions": True, "unset": False}
class Comment(Expression):
980class Comment(Expression):
981    arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
class ColumnConstraint(Expression):
984class ColumnConstraint(Expression):
985    arg_types = {"this": False, "kind": True}
class ColumnConstraintKind(Expression):
988class ColumnConstraintKind(Expression):
989    pass
class AutoIncrementColumnConstraint(ColumnConstraintKind):
992class AutoIncrementColumnConstraint(ColumnConstraintKind):
993    pass
class CaseSpecificColumnConstraint(ColumnConstraintKind):
996class CaseSpecificColumnConstraint(ColumnConstraintKind):
997    arg_types = {"not_": True}
class CharacterSetColumnConstraint(ColumnConstraintKind):
1000class CharacterSetColumnConstraint(ColumnConstraintKind):
1001    arg_types = {"this": True}
class CheckColumnConstraint(ColumnConstraintKind):
1004class CheckColumnConstraint(ColumnConstraintKind):
1005    pass
class CollateColumnConstraint(ColumnConstraintKind):
1008class CollateColumnConstraint(ColumnConstraintKind):
1009    pass
class CommentColumnConstraint(ColumnConstraintKind):
1012class CommentColumnConstraint(ColumnConstraintKind):
1013    pass
class CompressColumnConstraint(ColumnConstraintKind):
1016class CompressColumnConstraint(ColumnConstraintKind):
1017    pass
class DateFormatColumnConstraint(ColumnConstraintKind):
1020class DateFormatColumnConstraint(ColumnConstraintKind):
1021    arg_types = {"this": True}
class DefaultColumnConstraint(ColumnConstraintKind):
1024class DefaultColumnConstraint(ColumnConstraintKind):
1025    pass
class EncodeColumnConstraint(ColumnConstraintKind):
1028class EncodeColumnConstraint(ColumnConstraintKind):
1029    pass
class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1032class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1033    # this: True -> ALWAYS, this: False -> BY DEFAULT
1034    arg_types = {
1035        "this": False,
1036        "start": False,
1037        "increment": False,
1038        "minvalue": False,
1039        "maxvalue": False,
1040        "cycle": False,
1041    }
class InlineLengthColumnConstraint(ColumnConstraintKind):
1044class InlineLengthColumnConstraint(ColumnConstraintKind):
1045    pass
class NotNullColumnConstraint(ColumnConstraintKind):
1048class NotNullColumnConstraint(ColumnConstraintKind):
1049    arg_types = {"allow_null": False}
class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1052class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1053    arg_types = {"desc": False}
class TitleColumnConstraint(ColumnConstraintKind):
1056class TitleColumnConstraint(ColumnConstraintKind):
1057    pass
class UniqueColumnConstraint(ColumnConstraintKind):
1060class UniqueColumnConstraint(ColumnConstraintKind):
1061    arg_types: t.Dict[str, t.Any] = {}
class UppercaseColumnConstraint(ColumnConstraintKind):
1064class UppercaseColumnConstraint(ColumnConstraintKind):
1065    arg_types: t.Dict[str, t.Any] = {}
class PathColumnConstraint(ColumnConstraintKind):
1068class PathColumnConstraint(ColumnConstraintKind):
1069    pass
class Constraint(Expression):
1072class Constraint(Expression):
1073    arg_types = {"this": True, "expressions": True}
class Delete(Expression):
1076class Delete(Expression):
1077    arg_types = {"with": False, "this": False, "using": False, "where": False, "returning": False}
1078
1079    def delete(
1080        self,
1081        table: ExpOrStr,
1082        dialect: DialectType = None,
1083        copy: bool = True,
1084        **opts,
1085    ) -> Delete:
1086        """
1087        Create a DELETE expression or replace the table on an existing DELETE expression.
1088
1089        Example:
1090            >>> delete("tbl").sql()
1091            'DELETE FROM tbl'
1092
1093        Args:
1094            table: the table from which to delete.
1095            dialect: the dialect used to parse the input expression.
1096            copy: if `False`, modify this expression instance in-place.
1097            opts: other options to use to parse the input expressions.
1098
1099        Returns:
1100            Delete: the modified expression.
1101        """
1102        return _apply_builder(
1103            expression=table,
1104            instance=self,
1105            arg="this",
1106            dialect=dialect,
1107            into=Table,
1108            copy=copy,
1109            **opts,
1110        )
1111
1112    def where(
1113        self,
1114        *expressions: ExpOrStr,
1115        append: bool = True,
1116        dialect: DialectType = None,
1117        copy: bool = True,
1118        **opts,
1119    ) -> Delete:
1120        """
1121        Append to or set the WHERE expressions.
1122
1123        Example:
1124            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1125            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1126
1127        Args:
1128            *expressions: the SQL code strings to parse.
1129                If an `Expression` instance is passed, it will be used as-is.
1130                Multiple expressions are combined with an AND operator.
1131            append: if `True`, AND the new expressions to any existing expression.
1132                Otherwise, this resets the expression.
1133            dialect: the dialect used to parse the input expressions.
1134            copy: if `False`, modify this expression instance in-place.
1135            opts: other options to use to parse the input expressions.
1136
1137        Returns:
1138            Delete: the modified expression.
1139        """
1140        return _apply_conjunction_builder(
1141            *expressions,
1142            instance=self,
1143            arg="where",
1144            append=append,
1145            into=Where,
1146            dialect=dialect,
1147            copy=copy,
1148            **opts,
1149        )
1150
1151    def returning(
1152        self,
1153        expression: ExpOrStr,
1154        dialect: DialectType = None,
1155        copy: bool = True,
1156        **opts,
1157    ) -> Delete:
1158        """
1159        Set the RETURNING expression. Not supported by all dialects.
1160
1161        Example:
1162            >>> delete("tbl").returning("*", dialect="postgres").sql()
1163            'DELETE FROM tbl RETURNING *'
1164
1165        Args:
1166            expression: the SQL code strings to parse.
1167                If an `Expression` instance is passed, it will be used as-is.
1168            dialect: the dialect used to parse the input expressions.
1169            copy: if `False`, modify this expression instance in-place.
1170            opts: other options to use to parse the input expressions.
1171
1172        Returns:
1173            Delete: the modified expression.
1174        """
1175        return _apply_builder(
1176            expression=expression,
1177            instance=self,
1178            arg="returning",
1179            prefix="RETURNING",
1180            dialect=dialect,
1181            copy=copy,
1182            into=Returning,
1183            **opts,
1184        )
def delete( self, table: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Delete:
1079    def delete(
1080        self,
1081        table: ExpOrStr,
1082        dialect: DialectType = None,
1083        copy: bool = True,
1084        **opts,
1085    ) -> Delete:
1086        """
1087        Create a DELETE expression or replace the table on an existing DELETE expression.
1088
1089        Example:
1090            >>> delete("tbl").sql()
1091            'DELETE FROM tbl'
1092
1093        Args:
1094            table: the table from which to delete.
1095            dialect: the dialect used to parse the input expression.
1096            copy: if `False`, modify this expression instance in-place.
1097            opts: other options to use to parse the input expressions.
1098
1099        Returns:
1100            Delete: the modified expression.
1101        """
1102        return _apply_builder(
1103            expression=table,
1104            instance=self,
1105            arg="this",
1106            dialect=dialect,
1107            into=Table,
1108            copy=copy,
1109            **opts,
1110        )

Create a DELETE expression or replace the table on an existing DELETE expression.

Example:
>>> delete("tbl").sql()
'DELETE FROM tbl'
Arguments:
  • table: the table from which to delete.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

def where( self, *expressions: Union[str, sqlglot.expressions.Expression], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Delete:
1112    def where(
1113        self,
1114        *expressions: ExpOrStr,
1115        append: bool = True,
1116        dialect: DialectType = None,
1117        copy: bool = True,
1118        **opts,
1119    ) -> Delete:
1120        """
1121        Append to or set the WHERE expressions.
1122
1123        Example:
1124            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1125            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1126
1127        Args:
1128            *expressions: the SQL code strings to parse.
1129                If an `Expression` instance is passed, it will be used as-is.
1130                Multiple expressions are combined with an AND operator.
1131            append: if `True`, AND the new expressions to any existing expression.
1132                Otherwise, this resets the expression.
1133            dialect: the dialect used to parse the input expressions.
1134            copy: if `False`, modify this expression instance in-place.
1135            opts: other options to use to parse the input expressions.
1136
1137        Returns:
1138            Delete: the modified expression.
1139        """
1140        return _apply_conjunction_builder(
1141            *expressions,
1142            instance=self,
1143            arg="where",
1144            append=append,
1145            into=Where,
1146            dialect=dialect,
1147            copy=copy,
1148            **opts,
1149        )

Append to or set the WHERE expressions.

Example:
>>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
"DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append: if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

def returning( self, expression: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Delete:
1151    def returning(
1152        self,
1153        expression: ExpOrStr,
1154        dialect: DialectType = None,
1155        copy: bool = True,
1156        **opts,
1157    ) -> Delete:
1158        """
1159        Set the RETURNING expression. Not supported by all dialects.
1160
1161        Example:
1162            >>> delete("tbl").returning("*", dialect="postgres").sql()
1163            'DELETE FROM tbl RETURNING *'
1164
1165        Args:
1166            expression: the SQL code strings to parse.
1167                If an `Expression` instance is passed, it will be used as-is.
1168            dialect: the dialect used to parse the input expressions.
1169            copy: if `False`, modify this expression instance in-place.
1170            opts: other options to use to parse the input expressions.
1171
1172        Returns:
1173            Delete: the modified expression.
1174        """
1175        return _apply_builder(
1176            expression=expression,
1177            instance=self,
1178            arg="returning",
1179            prefix="RETURNING",
1180            dialect=dialect,
1181            copy=copy,
1182            into=Returning,
1183            **opts,
1184        )

Set the RETURNING expression. Not supported by all dialects.

Example:
>>> delete("tbl").returning("*", dialect="postgres").sql()
'DELETE FROM tbl RETURNING *'
Arguments:
  • expression: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

class Drop(Expression):
1187class Drop(Expression):
1188    arg_types = {
1189        "this": False,
1190        "kind": False,
1191        "exists": False,
1192        "temporary": False,
1193        "materialized": False,
1194        "cascade": False,
1195    }
class Filter(Expression):
1198class Filter(Expression):
1199    arg_types = {"this": True, "expression": True}
class Check(Expression):
1202class Check(Expression):
1203    pass
class Directory(Expression):
1206class Directory(Expression):
1207    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1208    arg_types = {"this": True, "local": False, "row_format": False}
class ForeignKey(Expression):
1211class ForeignKey(Expression):
1212    arg_types = {
1213        "expressions": True,
1214        "reference": False,
1215        "delete": False,
1216        "update": False,
1217    }
class PrimaryKey(Expression):
1220class PrimaryKey(Expression):
1221    arg_types = {"expressions": True, "options": False}
class Unique(Expression):
1224class Unique(Expression):
1225    arg_types = {"expressions": True}
class Into(Expression):
1230class Into(Expression):
1231    arg_types = {"this": True, "temporary": False, "unlogged": False}
class From(Expression):
1234class From(Expression):
1235    arg_types = {"expressions": True}
class Having(Expression):
1238class Having(Expression):
1239    pass
class Hint(Expression):
1242class Hint(Expression):
1243    arg_types = {"expressions": True}
class JoinHint(Expression):
1246class JoinHint(Expression):
1247    arg_types = {"this": True, "expressions": True}
class Identifier(Expression):
1250class Identifier(Expression):
1251    arg_types = {"this": True, "quoted": False}
1252
1253    @property
1254    def quoted(self):
1255        return bool(self.args.get("quoted"))
1256
1257    @property
1258    def hashable_args(self) -> t.Any:
1259        if self.quoted and any(char.isupper() for char in self.this):
1260            return (self.this, self.quoted)
1261        return self.this.lower()
1262
1263    @property
1264    def output_name(self):
1265        return self.name
output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class Index(Expression):
1268class Index(Expression):
1269    arg_types = {
1270        "this": False,
1271        "table": False,
1272        "where": False,
1273        "columns": False,
1274        "unique": False,
1275        "primary": False,
1276        "amp": False,  # teradata
1277    }
class Insert(Expression):
1280class Insert(Expression):
1281    arg_types = {
1282        "with": False,
1283        "this": True,
1284        "expression": False,
1285        "returning": False,
1286        "overwrite": False,
1287        "exists": False,
1288        "partition": False,
1289        "alternative": False,
1290    }
class Returning(Expression):
1293class Returning(Expression):
1294    arg_types = {"expressions": True}
class Introducer(Expression):
1298class Introducer(Expression):
1299    arg_types = {"this": True, "expression": True}
class National(Expression):
1303class National(Expression):
1304    pass
class LoadData(Expression):
1307class LoadData(Expression):
1308    arg_types = {
1309        "this": True,
1310        "local": False,
1311        "overwrite": False,
1312        "inpath": True,
1313        "partition": False,
1314        "input_format": False,
1315        "serde": False,
1316    }
class Partition(Expression):
1319class Partition(Expression):
1320    arg_types = {"expressions": True}
class Fetch(Expression):
1323class Fetch(Expression):
1324    arg_types = {"direction": False, "count": False}
class Group(Expression):
1327class Group(Expression):
1328    arg_types = {
1329        "expressions": False,
1330        "grouping_sets": False,
1331        "cube": False,
1332        "rollup": False,
1333    }
class Lambda(Expression):
1336class Lambda(Expression):
1337    arg_types = {"this": True, "expressions": True}
class Limit(Expression):
1340class Limit(Expression):
1341    arg_types = {"this": False, "expression": True}
class Literal(Condition):
1344class Literal(Condition):
1345    arg_types = {"this": True, "is_string": True}
1346
1347    @property
1348    def hashable_args(self) -> t.Any:
1349        return (self.this, self.args.get("is_string"))
1350
1351    @classmethod
1352    def number(cls, number) -> Literal:
1353        return cls(this=str(number), is_string=False)
1354
1355    @classmethod
1356    def string(cls, string) -> Literal:
1357        return cls(this=str(string), is_string=True)
1358
1359    @property
1360    def output_name(self):
1361        return self.name
@classmethod
def number(cls, number) -> sqlglot.expressions.Literal:
1351    @classmethod
1352    def number(cls, number) -> Literal:
1353        return cls(this=str(number), is_string=False)
@classmethod
def string(cls, string) -> sqlglot.expressions.Literal:
1355    @classmethod
1356    def string(cls, string) -> Literal:
1357        return cls(this=str(string), is_string=True)
output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class Join(Expression):
1364class Join(Expression):
1365    arg_types = {
1366        "this": True,
1367        "on": False,
1368        "side": False,
1369        "kind": False,
1370        "using": False,
1371        "natural": False,
1372    }
1373
1374    @property
1375    def kind(self):
1376        return self.text("kind").upper()
1377
1378    @property
1379    def side(self):
1380        return self.text("side").upper()
1381
1382    @property
1383    def alias_or_name(self):
1384        return self.this.alias_or_name
1385
1386    def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1387        """
1388        Append to or set the ON expressions.
1389
1390        Example:
1391            >>> import sqlglot
1392            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1393            'JOIN x ON y = 1'
1394
1395        Args:
1396            *expressions (str | Expression): the SQL code strings to parse.
1397                If an `Expression` instance is passed, it will be used as-is.
1398                Multiple expressions are combined with an AND operator.
1399            append (bool): if `True`, AND the new expressions to any existing expression.
1400                Otherwise, this resets the expression.
1401            dialect (str): the dialect used to parse the input expressions.
1402            copy (bool): if `False`, modify this expression instance in-place.
1403            opts (kwargs): other options to use to parse the input expressions.
1404
1405        Returns:
1406            Join: the modified join expression.
1407        """
1408        join = _apply_conjunction_builder(
1409            *expressions,
1410            instance=self,
1411            arg="on",
1412            append=append,
1413            dialect=dialect,
1414            copy=copy,
1415            **opts,
1416        )
1417
1418        if join.kind == "CROSS":
1419            join.set("kind", None)
1420
1421        return join
1422
1423    def using(self, *expressions, append=True, dialect=None, copy=True, **opts):
1424        """
1425        Append to or set the USING expressions.
1426
1427        Example:
1428            >>> import sqlglot
1429            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1430            'JOIN x USING (foo, bla)'
1431
1432        Args:
1433            *expressions (str | Expression): the SQL code strings to parse.
1434                If an `Expression` instance is passed, it will be used as-is.
1435            append (bool): if `True`, concatenate the new expressions to the existing "using" list.
1436                Otherwise, this resets the expression.
1437            dialect (str): the dialect used to parse the input expressions.
1438            copy (bool): if `False`, modify this expression instance in-place.
1439            opts (kwargs): other options to use to parse the input expressions.
1440
1441        Returns:
1442            Join: the modified join expression.
1443        """
1444        join = _apply_list_builder(
1445            *expressions,
1446            instance=self,
1447            arg="using",
1448            append=append,
1449            dialect=dialect,
1450            copy=copy,
1451            **opts,
1452        )
1453
1454        if join.kind == "CROSS":
1455            join.set("kind", None)
1456
1457        return join
def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1386    def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1387        """
1388        Append to or set the ON expressions.
1389
1390        Example:
1391            >>> import sqlglot
1392            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1393            'JOIN x ON y = 1'
1394
1395        Args:
1396            *expressions (str | Expression): the SQL code strings to parse.
1397                If an `Expression` instance is passed, it will be used as-is.
1398                Multiple expressions are combined with an AND operator.
1399            append (bool): if `True`, AND the new expressions to any existing expression.
1400                Otherwise, this resets the expression.
1401            dialect (str): the dialect used to parse the input expressions.
1402            copy (bool): if `False`, modify this expression instance in-place.
1403            opts (kwargs): other options to use to parse the input expressions.
1404
1405        Returns:
1406            Join: the modified join expression.
1407        """
1408        join = _apply_conjunction_builder(
1409            *expressions,
1410            instance=self,
1411            arg="on",
1412            append=append,
1413            dialect=dialect,
1414            copy=copy,
1415            **opts,
1416        )
1417
1418        if join.kind == "CROSS":
1419            join.set("kind", None)
1420
1421        return join

Append to or set the ON expressions.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
'JOIN x ON y = 1'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append (bool): if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Join: the modified join expression.

def using(self, *expressions, append=True, dialect=None, copy=True, **opts):
1423    def using(self, *expressions, append=True, dialect=None, copy=True, **opts):
1424        """
1425        Append to or set the USING expressions.
1426
1427        Example:
1428            >>> import sqlglot
1429            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1430            'JOIN x USING (foo, bla)'
1431
1432        Args:
1433            *expressions (str | Expression): the SQL code strings to parse.
1434                If an `Expression` instance is passed, it will be used as-is.
1435            append (bool): if `True`, concatenate the new expressions to the existing "using" list.
1436                Otherwise, this resets the expression.
1437            dialect (str): the dialect used to parse the input expressions.
1438            copy (bool): if `False`, modify this expression instance in-place.
1439            opts (kwargs): other options to use to parse the input expressions.
1440
1441        Returns:
1442            Join: the modified join expression.
1443        """
1444        join = _apply_list_builder(
1445            *expressions,
1446            instance=self,
1447            arg="using",
1448            append=append,
1449            dialect=dialect,
1450            copy=copy,
1451            **opts,
1452        )
1453
1454        if join.kind == "CROSS":
1455            join.set("kind", None)
1456
1457        return join

Append to or set the USING expressions.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
'JOIN x USING (foo, bla)'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append (bool): if True, concatenate the new expressions to the existing "using" list. Otherwise, this resets the expression.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Join: the modified join expression.

class Lateral(UDTF):
1460class Lateral(UDTF):
1461    arg_types = {"this": True, "view": False, "outer": False, "alias": False}
class MatchRecognize(Expression):
1464class MatchRecognize(Expression):
1465    arg_types = {
1466        "partition_by": False,
1467        "order": False,
1468        "measures": False,
1469        "rows": False,
1470        "after": False,
1471        "pattern": False,
1472        "define": False,
1473    }
class Final(Expression):
1478class Final(Expression):
1479    pass
class Offset(Expression):
1482class Offset(Expression):
1483    arg_types = {"this": False, "expression": True}
class Order(Expression):
1486class Order(Expression):
1487    arg_types = {"this": False, "expressions": True}
class Cluster(Order):
1492class Cluster(Order):
1493    pass
class Distribute(Order):
1496class Distribute(Order):
1497    pass
class Sort(Order):
1500class Sort(Order):
1501    pass
class Ordered(Expression):
1504class Ordered(Expression):
1505    arg_types = {"this": True, "desc": True, "nulls_first": True}
class Property(Expression):
1508class Property(Expression):
1509    arg_types = {"this": True, "value": True}
class AfterJournalProperty(Property):
1512class AfterJournalProperty(Property):
1513    arg_types = {"no": True, "dual": False, "local": False}
class AlgorithmProperty(Property):
1516class AlgorithmProperty(Property):
1517    arg_types = {"this": True}
class AutoIncrementProperty(Property):
1520class AutoIncrementProperty(Property):
1521    arg_types = {"this": True}
class BlockCompressionProperty(Property):
1524class BlockCompressionProperty(Property):
1525    arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
class CharacterSetProperty(Property):
1528class CharacterSetProperty(Property):
1529    arg_types = {"this": True, "default": True}
class ChecksumProperty(Property):
1532class ChecksumProperty(Property):
1533    arg_types = {"on": False, "default": False}
class CollateProperty(Property):
1536class CollateProperty(Property):
1537    arg_types = {"this": True}
class DataBlocksizeProperty(Property):
1540class DataBlocksizeProperty(Property):
1541    arg_types = {"size": False, "units": False, "min": False, "default": False}
class DefinerProperty(Property):
1544class DefinerProperty(Property):
1545    arg_types = {"this": True}
class DistKeyProperty(Property):
1548class DistKeyProperty(Property):
1549    arg_types = {"this": True}
class DistStyleProperty(Property):
1552class DistStyleProperty(Property):
1553    arg_types = {"this": True}
class EngineProperty(Property):
1556class EngineProperty(Property):
1557    arg_types = {"this": True}
class ExecuteAsProperty(Property):
1560class ExecuteAsProperty(Property):
1561    arg_types = {"this": True}
class ExternalProperty(Property):
1564class ExternalProperty(Property):
1565    arg_types = {"this": False}
class FallbackProperty(Property):
1568class FallbackProperty(Property):
1569    arg_types = {"no": True, "protection": False}
class FileFormatProperty(Property):
1572class FileFormatProperty(Property):
1573    arg_types = {"this": True}
class FreespaceProperty(Property):
1576class FreespaceProperty(Property):
1577    arg_types = {"this": True, "percent": False}
class IsolatedLoadingProperty(Property):
1580class IsolatedLoadingProperty(Property):
1581    arg_types = {
1582        "no": True,
1583        "concurrent": True,
1584        "for_all": True,
1585        "for_insert": True,
1586        "for_none": True,
1587    }
class JournalProperty(Property):
1590class JournalProperty(Property):
1591    arg_types = {"no": True, "dual": False, "before": False}
class LanguageProperty(Property):
1594class LanguageProperty(Property):
1595    arg_types = {"this": True}
class LikeProperty(Property):
1598class LikeProperty(Property):
1599    arg_types = {"this": True, "expressions": False}
class LocationProperty(Property):
1602class LocationProperty(Property):
1603    arg_types = {"this": True}
class LockingProperty(Property):
1606class LockingProperty(Property):
1607    arg_types = {
1608        "this": False,
1609        "kind": True,
1610        "for_or_in": True,
1611        "lock_type": True,
1612        "override": False,
1613    }
class LogProperty(Property):
1616class LogProperty(Property):
1617    arg_types = {"no": True}
class MaterializedProperty(Property):
1620class MaterializedProperty(Property):
1621    arg_types = {"this": False}
class MergeBlockRatioProperty(Property):
1624class MergeBlockRatioProperty(Property):
1625    arg_types = {"this": False, "no": False, "default": False, "percent": False}
class NoPrimaryIndexProperty(Property):
1628class NoPrimaryIndexProperty(Property):
1629    arg_types = {"this": False}
class OnCommitProperty(Property):
1632class OnCommitProperty(Property):
1633    arg_type = {"this": False}
class PartitionedByProperty(Property):
1636class PartitionedByProperty(Property):
1637    arg_types = {"this": True}
class ReturnsProperty(Property):
1640class ReturnsProperty(Property):
1641    arg_types = {"this": True, "is_table": False, "table": False}
class RowFormatDelimitedProperty(Property):
1644class RowFormatDelimitedProperty(Property):
1645    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
1646    arg_types = {
1647        "fields": False,
1648        "escaped": False,
1649        "collection_items": False,
1650        "map_keys": False,
1651        "lines": False,
1652        "null": False,
1653        "serde": False,
1654    }
class RowFormatSerdeProperty(Property):
1657class RowFormatSerdeProperty(Property):
1658    arg_types = {"this": True}
class SchemaCommentProperty(Property):
1661class SchemaCommentProperty(Property):
1662    arg_types = {"this": True}
class SerdeProperties(Property):
1665class SerdeProperties(Property):
1666    arg_types = {"expressions": True}
class SetProperty(Property):
1669class SetProperty(Property):
1670    arg_types = {"multi": True}
class SortKeyProperty(Property):
1673class SortKeyProperty(Property):
1674    arg_types = {"this": True, "compound": False}
class SqlSecurityProperty(Property):
1677class SqlSecurityProperty(Property):
1678    arg_types = {"definer": True}
class TableFormatProperty(Property):
1681class TableFormatProperty(Property):
1682    arg_types = {"this": True}
class TemporaryProperty(Property):
1685class TemporaryProperty(Property):
1686    arg_types = {"global_": True}
class TransientProperty(Property):
1689class TransientProperty(Property):
1690    arg_types = {"this": False}
class VolatilityProperty(Property):
1693class VolatilityProperty(Property):
1694    arg_types = {"this": True}
class WithDataProperty(Property):
1697class WithDataProperty(Property):
1698    arg_types = {"no": True, "statistics": False}
class WithJournalTableProperty(Property):
1701class WithJournalTableProperty(Property):
1702    arg_types = {"this": True}
class Properties(Expression):
1705class Properties(Expression):
1706    arg_types = {"expressions": True}
1707
1708    NAME_TO_PROPERTY = {
1709        "ALGORITHM": AlgorithmProperty,
1710        "AUTO_INCREMENT": AutoIncrementProperty,
1711        "CHARACTER SET": CharacterSetProperty,
1712        "COLLATE": CollateProperty,
1713        "COMMENT": SchemaCommentProperty,
1714        "DEFINER": DefinerProperty,
1715        "DISTKEY": DistKeyProperty,
1716        "DISTSTYLE": DistStyleProperty,
1717        "ENGINE": EngineProperty,
1718        "EXECUTE AS": ExecuteAsProperty,
1719        "FORMAT": FileFormatProperty,
1720        "LANGUAGE": LanguageProperty,
1721        "LOCATION": LocationProperty,
1722        "PARTITIONED_BY": PartitionedByProperty,
1723        "RETURNS": ReturnsProperty,
1724        "SORTKEY": SortKeyProperty,
1725        "TABLE_FORMAT": TableFormatProperty,
1726    }
1727
1728    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
1729
1730    # CREATE property locations
1731    # Form: schema specified
1732    #   create [POST_CREATE]
1733    #     table a [POST_NAME]
1734    #     (b int) [POST_SCHEMA]
1735    #     with ([POST_WITH])
1736    #     index (b) [POST_INDEX]
1737    #
1738    # Form: alias selection
1739    #   create [POST_CREATE]
1740    #     table a [POST_NAME]
1741    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
1742    #     index (c) [POST_INDEX]
1743    class Location(AutoName):
1744        POST_CREATE = auto()
1745        POST_NAME = auto()
1746        POST_SCHEMA = auto()
1747        POST_WITH = auto()
1748        POST_ALIAS = auto()
1749        POST_EXPRESSION = auto()
1750        POST_INDEX = auto()
1751        UNSUPPORTED = auto()
1752
1753    @classmethod
1754    def from_dict(cls, properties_dict) -> Properties:
1755        expressions = []
1756        for key, value in properties_dict.items():
1757            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
1758            if property_cls:
1759                expressions.append(property_cls(this=convert(value)))
1760            else:
1761                expressions.append(Property(this=Literal.string(key), value=convert(value)))
1762
1763        return cls(expressions=expressions)
@classmethod
def from_dict(cls, properties_dict) -> sqlglot.expressions.Properties:
1753    @classmethod
1754    def from_dict(cls, properties_dict) -> Properties:
1755        expressions = []
1756        for key, value in properties_dict.items():
1757            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
1758            if property_cls:
1759                expressions.append(property_cls(this=convert(value)))
1760            else:
1761                expressions.append(Property(this=Literal.string(key), value=convert(value)))
1762
1763        return cls(expressions=expressions)
class Properties.Location(sqlglot.helper.AutoName):
1743    class Location(AutoName):
1744        POST_CREATE = auto()
1745        POST_NAME = auto()
1746        POST_SCHEMA = auto()
1747        POST_WITH = auto()
1748        POST_ALIAS = auto()
1749        POST_EXPRESSION = auto()
1750        POST_INDEX = auto()
1751        UNSUPPORTED = auto()

An enumeration.

POST_CREATE = <Location.POST_CREATE: 'POST_CREATE'>
POST_NAME = <Location.POST_NAME: 'POST_NAME'>
POST_SCHEMA = <Location.POST_SCHEMA: 'POST_SCHEMA'>
POST_WITH = <Location.POST_WITH: 'POST_WITH'>
POST_ALIAS = <Location.POST_ALIAS: 'POST_ALIAS'>
POST_EXPRESSION = <Location.POST_EXPRESSION: 'POST_EXPRESSION'>
POST_INDEX = <Location.POST_INDEX: 'POST_INDEX'>
UNSUPPORTED = <Location.UNSUPPORTED: 'UNSUPPORTED'>
Inherited Members
enum.Enum
name
value
class Qualify(Expression):
1766class Qualify(Expression):
1767    pass
class Return(Expression):
1771class Return(Expression):
1772    pass
class Reference(Expression):
1775class Reference(Expression):
1776    arg_types = {"this": True, "expressions": False, "options": False}
class Tuple(Expression):
1779class Tuple(Expression):
1780    arg_types = {"expressions": False}
class Subqueryable(Unionable):
1783class Subqueryable(Unionable):
1784    def subquery(self, alias=None, copy=True) -> Subquery:
1785        """
1786        Convert this expression to an aliased expression that can be used as a Subquery.
1787
1788        Example:
1789            >>> subquery = Select().select("x").from_("tbl").subquery()
1790            >>> Select().select("x").from_(subquery).sql()
1791            'SELECT x FROM (SELECT x FROM tbl)'
1792
1793        Args:
1794            alias (str | Identifier): an optional alias for the subquery
1795            copy (bool): if `False`, modify this expression instance in-place.
1796
1797        Returns:
1798            Alias: the subquery
1799        """
1800        instance = _maybe_copy(self, copy)
1801        return Subquery(
1802            this=instance,
1803            alias=TableAlias(this=to_identifier(alias)) if alias else None,
1804        )
1805
1806    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1807        raise NotImplementedError
1808
1809    @property
1810    def ctes(self):
1811        with_ = self.args.get("with")
1812        if not with_:
1813            return []
1814        return with_.expressions
1815
1816    @property
1817    def selects(self):
1818        raise NotImplementedError("Subqueryable objects must implement `selects`")
1819
1820    @property
1821    def named_selects(self):
1822        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
1823
1824    def with_(
1825        self,
1826        alias,
1827        as_,
1828        recursive=None,
1829        append=True,
1830        dialect=None,
1831        copy=True,
1832        **opts,
1833    ):
1834        """
1835        Append to or set the common table expressions.
1836
1837        Example:
1838            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
1839            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
1840
1841        Args:
1842            alias (str | Expression): the SQL code string to parse as the table name.
1843                If an `Expression` instance is passed, this is used as-is.
1844            as_ (str | Expression): the SQL code string to parse as the table expression.
1845                If an `Expression` instance is passed, it will be used as-is.
1846            recursive (bool): set the RECURSIVE part of the expression. Defaults to `False`.
1847            append (bool): if `True`, add to any existing expressions.
1848                Otherwise, this resets the expressions.
1849            dialect (str): the dialect used to parse the input expression.
1850            copy (bool): if `False`, modify this expression instance in-place.
1851            opts (kwargs): other options to use to parse the input expressions.
1852
1853        Returns:
1854            Select: the modified expression.
1855        """
1856        alias_expression = maybe_parse(
1857            alias,
1858            dialect=dialect,
1859            into=TableAlias,
1860            **opts,
1861        )
1862        as_expression = maybe_parse(
1863            as_,
1864            dialect=dialect,
1865            **opts,
1866        )
1867        cte = CTE(
1868            this=as_expression,
1869            alias=alias_expression,
1870        )
1871        return _apply_child_list_builder(
1872            cte,
1873            instance=self,
1874            arg="with",
1875            append=append,
1876            copy=copy,
1877            into=With,
1878            properties={"recursive": recursive or False},
1879        )
def subquery(self, alias=None, copy=True) -> sqlglot.expressions.Subquery:
1784    def subquery(self, alias=None, copy=True) -> Subquery:
1785        """
1786        Convert this expression to an aliased expression that can be used as a Subquery.
1787
1788        Example:
1789            >>> subquery = Select().select("x").from_("tbl").subquery()
1790            >>> Select().select("x").from_(subquery).sql()
1791            'SELECT x FROM (SELECT x FROM tbl)'
1792
1793        Args:
1794            alias (str | Identifier): an optional alias for the subquery
1795            copy (bool): if `False`, modify this expression instance in-place.
1796
1797        Returns:
1798            Alias: the subquery
1799        """
1800        instance = _maybe_copy(self, copy)
1801        return Subquery(
1802            this=instance,
1803            alias=TableAlias(this=to_identifier(alias)) if alias else None,
1804        )

Convert this expression to an aliased expression that can be used as a Subquery.

Example:
>>> subquery = Select().select("x").from_("tbl").subquery()
>>> Select().select("x").from_(subquery).sql()
'SELECT x FROM (SELECT x FROM tbl)'
Arguments:
  • alias (str | Identifier): an optional alias for the subquery
  • copy (bool): if False, modify this expression instance in-place.
Returns:

Alias: the subquery

def limit( self, expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
1806    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1807        raise NotImplementedError
def with_( self, alias, as_, recursive=None, append=True, dialect=None, copy=True, **opts):
1824    def with_(
1825        self,
1826        alias,
1827        as_,
1828        recursive=None,
1829        append=True,
1830        dialect=None,
1831        copy=True,
1832        **opts,
1833    ):
1834        """
1835        Append to or set the common table expressions.
1836
1837        Example:
1838            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
1839            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
1840
1841        Args:
1842            alias (str | Expression): the SQL code string to parse as the table name.
1843                If an `Expression` instance is passed, this is used as-is.
1844            as_ (str | Expression): the SQL code string to parse as the table expression.
1845                If an `Expression` instance is passed, it will be used as-is.
1846            recursive (bool): set the RECURSIVE part of the expression. Defaults to `False`.
1847            append (bool): if `True`, add to any existing expressions.
1848                Otherwise, this resets the expressions.
1849            dialect (str): the dialect used to parse the input expression.
1850            copy (bool): if `False`, modify this expression instance in-place.
1851            opts (kwargs): other options to use to parse the input expressions.
1852
1853        Returns:
1854            Select: the modified expression.
1855        """
1856        alias_expression = maybe_parse(
1857            alias,
1858            dialect=dialect,
1859            into=TableAlias,
1860            **opts,
1861        )
1862        as_expression = maybe_parse(
1863            as_,
1864            dialect=dialect,
1865            **opts,
1866        )
1867        cte = CTE(
1868            this=as_expression,
1869            alias=alias_expression,
1870        )
1871        return _apply_child_list_builder(
1872            cte,
1873            instance=self,
1874            arg="with",
1875            append=append,
1876            copy=copy,
1877            into=With,
1878            properties={"recursive": recursive or False},
1879        )

Append to or set the common table expressions.

Example:
>>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
Arguments:
  • alias (str | Expression): the SQL code string to parse as the table name. If an Expression instance is passed, this is used as-is.
  • as_ (str | Expression): the SQL code string to parse as the table expression. If an Expression instance is passed, it will be used as-is.
  • recursive (bool): set the RECURSIVE part of the expression. Defaults to False.
  • append (bool): if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

class Table(Expression):
1903class Table(Expression):
1904    arg_types = {
1905        "this": True,
1906        "alias": False,
1907        "db": False,
1908        "catalog": False,
1909        "laterals": False,
1910        "joins": False,
1911        "pivots": False,
1912        "hints": False,
1913        "system_time": False,
1914    }
1915
1916    @property
1917    def db(self) -> str:
1918        return self.text("db")
1919
1920    @property
1921    def catalog(self) -> str:
1922        return self.text("catalog")
class SystemTime(Expression):
1926class SystemTime(Expression):
1927    arg_types = {
1928        "this": False,
1929        "expression": False,
1930        "kind": True,
1931    }
class Union(Subqueryable):
1934class Union(Subqueryable):
1935    arg_types = {
1936        "with": False,
1937        "this": True,
1938        "expression": True,
1939        "distinct": False,
1940        **QUERY_MODIFIERS,
1941    }
1942
1943    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1944        """
1945        Set the LIMIT expression.
1946
1947        Example:
1948            >>> select("1").union(select("1")).limit(1).sql()
1949            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
1950
1951        Args:
1952            expression (str | int | Expression): the SQL code string to parse.
1953                This can also be an integer.
1954                If a `Limit` instance is passed, this is used as-is.
1955                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
1956            dialect (str): the dialect used to parse the input expression.
1957            copy (bool): if `False`, modify this expression instance in-place.
1958            opts (kwargs): other options to use to parse the input expressions.
1959
1960        Returns:
1961            Select: The limited subqueryable.
1962        """
1963        return (
1964            select("*")
1965            .from_(self.subquery(alias="_l_0", copy=copy))
1966            .limit(expression, dialect=dialect, copy=False, **opts)
1967        )
1968
1969    def select(
1970        self,
1971        *expressions: ExpOrStr,
1972        append: bool = True,
1973        dialect: DialectType = None,
1974        copy: bool = True,
1975        **opts,
1976    ) -> Union:
1977        """Append to or set the SELECT of the union recursively.
1978
1979        Example:
1980            >>> from sqlglot import parse_one
1981            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
1982            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
1983
1984        Args:
1985            *expressions: the SQL code strings to parse.
1986                If an `Expression` instance is passed, it will be used as-is.
1987            append: if `True`, add to any existing expressions.
1988                Otherwise, this resets the expressions.
1989            dialect: the dialect used to parse the input expressions.
1990            copy: if `False`, modify this expression instance in-place.
1991            opts: other options to use to parse the input expressions.
1992
1993        Returns:
1994            Union: the modified expression.
1995        """
1996        this = self.copy() if copy else self
1997        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
1998        this.expression.unnest().select(
1999            *expressions, append=append, dialect=dialect, copy=False, **opts
2000        )
2001        return this
2002
2003    @property
2004    def named_selects(self):
2005        return self.this.unnest().named_selects
2006
2007    @property
2008    def is_star(self) -> bool:
2009        return self.this.is_star or self.expression.is_star
2010
2011    @property
2012    def selects(self):
2013        return self.this.unnest().selects
2014
2015    @property
2016    def left(self):
2017        return self.this
2018
2019    @property
2020    def right(self):
2021        return self.expression
def limit( self, expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
1943    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1944        """
1945        Set the LIMIT expression.
1946
1947        Example:
1948            >>> select("1").union(select("1")).limit(1).sql()
1949            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
1950
1951        Args:
1952            expression (str | int | Expression): the SQL code string to parse.
1953                This can also be an integer.
1954                If a `Limit` instance is passed, this is used as-is.
1955                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
1956            dialect (str): the dialect used to parse the input expression.
1957            copy (bool): if `False`, modify this expression instance in-place.
1958            opts (kwargs): other options to use to parse the input expressions.
1959
1960        Returns:
1961            Select: The limited subqueryable.
1962        """
1963        return (
1964            select("*")
1965            .from_(self.subquery(alias="_l_0", copy=copy))
1966            .limit(expression, dialect=dialect, copy=False, **opts)
1967        )

Set the LIMIT expression.

Example:
>>> select("1").union(select("1")).limit(1).sql()
'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
Arguments:
  • expression (str | int | Expression): the SQL code string to parse. This can also be an integer. If a Limit instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Limit.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: The limited subqueryable.

def select( self, *expressions: Union[str, sqlglot.expressions.Expression], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Union:
1969    def select(
1970        self,
1971        *expressions: ExpOrStr,
1972        append: bool = True,
1973        dialect: DialectType = None,
1974        copy: bool = True,
1975        **opts,
1976    ) -> Union:
1977        """Append to or set the SELECT of the union recursively.
1978
1979        Example:
1980            >>> from sqlglot import parse_one
1981            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
1982            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
1983
1984        Args:
1985            *expressions: the SQL code strings to parse.
1986                If an `Expression` instance is passed, it will be used as-is.
1987            append: if `True`, add to any existing expressions.
1988                Otherwise, this resets the expressions.
1989            dialect: the dialect used to parse the input expressions.
1990            copy: if `False`, modify this expression instance in-place.
1991            opts: other options to use to parse the input expressions.
1992
1993        Returns:
1994            Union: the modified expression.
1995        """
1996        this = self.copy() if copy else self
1997        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
1998        this.expression.unnest().select(
1999            *expressions, append=append, dialect=dialect, copy=False, **opts
2000        )
2001        return this

Append to or set the SELECT of the union recursively.

Example:
>>> from sqlglot import parse_one
>>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Union: the modified expression.

is_star: bool

Checks whether an expression is a star.

class Except(Union):
2024class Except(Union):
2025    pass
class Intersect(Union):
2028class Intersect(Union):
2029    pass
class Unnest(UDTF):
2032class Unnest(UDTF):
2033    arg_types = {
2034        "expressions": True,
2035        "ordinality": False,
2036        "alias": False,
2037        "offset": False,
2038    }
class Update(Expression):
2041class Update(Expression):
2042    arg_types = {
2043        "with": False,
2044        "this": False,
2045        "expressions": True,
2046        "from": False,
2047        "where": False,
2048        "returning": False,
2049    }
class Values(UDTF):
2052class Values(UDTF):
2053    arg_types = {
2054        "expressions": True,
2055        "ordinality": False,
2056        "alias": False,
2057    }
class Var(Expression):
2060class Var(Expression):
2061    pass
class Schema(Expression):
2064class Schema(Expression):
2065    arg_types = {"this": False, "expressions": False}
class Lock(Expression):
2070class Lock(Expression):
2071    arg_types = {"update": True}
class Select(Subqueryable):
2074class Select(Subqueryable):
2075    arg_types = {
2076        "with": False,
2077        "kind": False,
2078        "expressions": False,
2079        "hint": False,
2080        "distinct": False,
2081        "into": False,
2082        "from": False,
2083        **QUERY_MODIFIERS,
2084    }
2085
2086    def from_(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2087        """
2088        Set the FROM expression.
2089
2090        Example:
2091            >>> Select().from_("tbl").select("x").sql()
2092            'SELECT x FROM tbl'
2093
2094        Args:
2095            *expressions (str | Expression): the SQL code strings to parse.
2096                If a `From` instance is passed, this is used as-is.
2097                If another `Expression` instance is passed, it will be wrapped in a `From`.
2098            append (bool): if `True`, add to any existing expressions.
2099                Otherwise, this flattens all the `From` expression into a single expression.
2100            dialect (str): the dialect used to parse the input expression.
2101            copy (bool): if `False`, modify this expression instance in-place.
2102            opts (kwargs): other options to use to parse the input expressions.
2103
2104        Returns:
2105            Select: the modified expression.
2106        """
2107        return _apply_child_list_builder(
2108            *expressions,
2109            instance=self,
2110            arg="from",
2111            append=append,
2112            copy=copy,
2113            prefix="FROM",
2114            into=From,
2115            dialect=dialect,
2116            **opts,
2117        )
2118
2119    def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2120        """
2121        Set the GROUP BY expression.
2122
2123        Example:
2124            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2125            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2126
2127        Args:
2128            *expressions (str | Expression): the SQL code strings to parse.
2129                If a `Group` instance is passed, this is used as-is.
2130                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2131                If nothing is passed in then a group by is not applied to the expression
2132            append (bool): if `True`, add to any existing expressions.
2133                Otherwise, this flattens all the `Group` expression into a single expression.
2134            dialect (str): the dialect used to parse the input expression.
2135            copy (bool): if `False`, modify this expression instance in-place.
2136            opts (kwargs): other options to use to parse the input expressions.
2137
2138        Returns:
2139            Select: the modified expression.
2140        """
2141        if not expressions:
2142            return self if not copy else self.copy()
2143        return _apply_child_list_builder(
2144            *expressions,
2145            instance=self,
2146            arg="group",
2147            append=append,
2148            copy=copy,
2149            prefix="GROUP BY",
2150            into=Group,
2151            dialect=dialect,
2152            **opts,
2153        )
2154
2155    def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2156        """
2157        Set the ORDER BY expression.
2158
2159        Example:
2160            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2161            'SELECT x FROM tbl ORDER BY x DESC'
2162
2163        Args:
2164            *expressions (str | Expression): the SQL code strings to parse.
2165                If a `Group` instance is passed, this is used as-is.
2166                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2167            append (bool): if `True`, add to any existing expressions.
2168                Otherwise, this flattens all the `Order` expression into a single expression.
2169            dialect (str): the dialect used to parse the input expression.
2170            copy (bool): if `False`, modify this expression instance in-place.
2171            opts (kwargs): other options to use to parse the input expressions.
2172
2173        Returns:
2174            Select: the modified expression.
2175        """
2176        return _apply_child_list_builder(
2177            *expressions,
2178            instance=self,
2179            arg="order",
2180            append=append,
2181            copy=copy,
2182            prefix="ORDER BY",
2183            into=Order,
2184            dialect=dialect,
2185            **opts,
2186        )
2187
2188    def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2189        """
2190        Set the SORT BY expression.
2191
2192        Example:
2193            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql()
2194            'SELECT x FROM tbl SORT BY x DESC'
2195
2196        Args:
2197            *expressions (str | Expression): the SQL code strings to parse.
2198                If a `Group` instance is passed, this is used as-is.
2199                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2200            append (bool): if `True`, add to any existing expressions.
2201                Otherwise, this flattens all the `Order` expression into a single expression.
2202            dialect (str): the dialect used to parse the input expression.
2203            copy (bool): if `False`, modify this expression instance in-place.
2204            opts (kwargs): other options to use to parse the input expressions.
2205
2206        Returns:
2207            Select: the modified expression.
2208        """
2209        return _apply_child_list_builder(
2210            *expressions,
2211            instance=self,
2212            arg="sort",
2213            append=append,
2214            copy=copy,
2215            prefix="SORT BY",
2216            into=Sort,
2217            dialect=dialect,
2218            **opts,
2219        )
2220
2221    def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2222        """
2223        Set the CLUSTER BY expression.
2224
2225        Example:
2226            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql()
2227            'SELECT x FROM tbl CLUSTER BY x DESC'
2228
2229        Args:
2230            *expressions (str | Expression): the SQL code strings to parse.
2231                If a `Group` instance is passed, this is used as-is.
2232                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2233            append (bool): if `True`, add to any existing expressions.
2234                Otherwise, this flattens all the `Order` expression into a single expression.
2235            dialect (str): the dialect used to parse the input expression.
2236            copy (bool): if `False`, modify this expression instance in-place.
2237            opts (kwargs): other options to use to parse the input expressions.
2238
2239        Returns:
2240            Select: the modified expression.
2241        """
2242        return _apply_child_list_builder(
2243            *expressions,
2244            instance=self,
2245            arg="cluster",
2246            append=append,
2247            copy=copy,
2248            prefix="CLUSTER BY",
2249            into=Cluster,
2250            dialect=dialect,
2251            **opts,
2252        )
2253
2254    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2255        """
2256        Set the LIMIT expression.
2257
2258        Example:
2259            >>> Select().from_("tbl").select("x").limit(10).sql()
2260            'SELECT x FROM tbl LIMIT 10'
2261
2262        Args:
2263            expression (str | int | Expression): the SQL code string to parse.
2264                This can also be an integer.
2265                If a `Limit` instance is passed, this is used as-is.
2266                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2267            dialect (str): the dialect used to parse the input expression.
2268            copy (bool): if `False`, modify this expression instance in-place.
2269            opts (kwargs): other options to use to parse the input expressions.
2270
2271        Returns:
2272            Select: the modified expression.
2273        """
2274        return _apply_builder(
2275            expression=expression,
2276            instance=self,
2277            arg="limit",
2278            into=Limit,
2279            prefix="LIMIT",
2280            dialect=dialect,
2281            copy=copy,
2282            **opts,
2283        )
2284
2285    def offset(self, expression, dialect=None, copy=True, **opts) -> Select:
2286        """
2287        Set the OFFSET expression.
2288
2289        Example:
2290            >>> Select().from_("tbl").select("x").offset(10).sql()
2291            'SELECT x FROM tbl OFFSET 10'
2292
2293        Args:
2294            expression (str | int | Expression): the SQL code string to parse.
2295                This can also be an integer.
2296                If a `Offset` instance is passed, this is used as-is.
2297                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2298            dialect (str): the dialect used to parse the input expression.
2299            copy (bool): if `False`, modify this expression instance in-place.
2300            opts (kwargs): other options to use to parse the input expressions.
2301
2302        Returns:
2303            Select: the modified expression.
2304        """
2305        return _apply_builder(
2306            expression=expression,
2307            instance=self,
2308            arg="offset",
2309            into=Offset,
2310            prefix="OFFSET",
2311            dialect=dialect,
2312            copy=copy,
2313            **opts,
2314        )
2315
2316    def select(
2317        self,
2318        *expressions: ExpOrStr,
2319        append: bool = True,
2320        dialect: DialectType = None,
2321        copy: bool = True,
2322        **opts,
2323    ) -> Select:
2324        """
2325        Append to or set the SELECT expressions.
2326
2327        Example:
2328            >>> Select().select("x", "y").sql()
2329            'SELECT x, y'
2330
2331        Args:
2332            *expressions: the SQL code strings to parse.
2333                If an `Expression` instance is passed, it will be used as-is.
2334            append: if `True`, add to any existing expressions.
2335                Otherwise, this resets the expressions.
2336            dialect: the dialect used to parse the input expressions.
2337            copy: if `False`, modify this expression instance in-place.
2338            opts: other options to use to parse the input expressions.
2339
2340        Returns:
2341            Select: the modified expression.
2342        """
2343        return _apply_list_builder(
2344            *expressions,
2345            instance=self,
2346            arg="expressions",
2347            append=append,
2348            dialect=dialect,
2349            copy=copy,
2350            **opts,
2351        )
2352
2353    def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2354        """
2355        Append to or set the LATERAL expressions.
2356
2357        Example:
2358            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2359            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2360
2361        Args:
2362            *expressions (str | Expression): the SQL code strings to parse.
2363                If an `Expression` instance is passed, it will be used as-is.
2364            append (bool): if `True`, add to any existing expressions.
2365                Otherwise, this resets the expressions.
2366            dialect (str): the dialect used to parse the input expressions.
2367            copy (bool): if `False`, modify this expression instance in-place.
2368            opts (kwargs): other options to use to parse the input expressions.
2369
2370        Returns:
2371            Select: the modified expression.
2372        """
2373        return _apply_list_builder(
2374            *expressions,
2375            instance=self,
2376            arg="laterals",
2377            append=append,
2378            into=Lateral,
2379            prefix="LATERAL VIEW",
2380            dialect=dialect,
2381            copy=copy,
2382            **opts,
2383        )
2384
2385    def join(
2386        self,
2387        expression,
2388        on=None,
2389        using=None,
2390        append=True,
2391        join_type=None,
2392        join_alias=None,
2393        dialect=None,
2394        copy=True,
2395        **opts,
2396    ) -> Select:
2397        """
2398        Append to or set the JOIN expressions.
2399
2400        Example:
2401            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2402            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2403
2404            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2405            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2406
2407            Use `join_type` to change the type of join:
2408
2409            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2410            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2411
2412        Args:
2413            expression (str | Expression): the SQL code string to parse.
2414                If an `Expression` instance is passed, it will be used as-is.
2415            on (str | Expression): optionally specify the join "on" criteria as a SQL string.
2416                If an `Expression` instance is passed, it will be used as-is.
2417            using (str | Expression): optionally specify the join "using" criteria as a SQL string.
2418                If an `Expression` instance is passed, it will be used as-is.
2419            append (bool): if `True`, add to any existing expressions.
2420                Otherwise, this resets the expressions.
2421            join_type (str): If set, alter the parsed join type
2422            dialect (str): the dialect used to parse the input expressions.
2423            copy (bool): if `False`, modify this expression instance in-place.
2424            opts (kwargs): other options to use to parse the input expressions.
2425
2426        Returns:
2427            Select: the modified expression.
2428        """
2429        parse_args = {"dialect": dialect, **opts}
2430
2431        try:
2432            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2433        except ParseError:
2434            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2435
2436        join = expression if isinstance(expression, Join) else Join(this=expression)
2437
2438        if isinstance(join.this, Select):
2439            join.this.replace(join.this.subquery())
2440
2441        if join_type:
2442            natural: t.Optional[Token]
2443            side: t.Optional[Token]
2444            kind: t.Optional[Token]
2445
2446            natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2447
2448            if natural:
2449                join.set("natural", True)
2450            if side:
2451                join.set("side", side.text)
2452            if kind:
2453                join.set("kind", kind.text)
2454
2455        if on:
2456            on = and_(*ensure_collection(on), dialect=dialect, **opts)
2457            join.set("on", on)
2458
2459        if using:
2460            join = _apply_list_builder(
2461                *ensure_collection(using),
2462                instance=join,
2463                arg="using",
2464                append=append,
2465                copy=copy,
2466                **opts,
2467            )
2468
2469        if join_alias:
2470            join.set("this", alias_(join.this, join_alias, table=True))
2471        return _apply_list_builder(
2472            join,
2473            instance=self,
2474            arg="joins",
2475            append=append,
2476            copy=copy,
2477            **opts,
2478        )
2479
2480    def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2481        """
2482        Append to or set the WHERE expressions.
2483
2484        Example:
2485            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2486            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2487
2488        Args:
2489            *expressions (str | Expression): the SQL code strings to parse.
2490                If an `Expression` instance is passed, it will be used as-is.
2491                Multiple expressions are combined with an AND operator.
2492            append (bool): if `True`, AND the new expressions to any existing expression.
2493                Otherwise, this resets the expression.
2494            dialect (str): the dialect used to parse the input expressions.
2495            copy (bool): if `False`, modify this expression instance in-place.
2496            opts (kwargs): other options to use to parse the input expressions.
2497
2498        Returns:
2499            Select: the modified expression.
2500        """
2501        return _apply_conjunction_builder(
2502            *expressions,
2503            instance=self,
2504            arg="where",
2505            append=append,
2506            into=Where,
2507            dialect=dialect,
2508            copy=copy,
2509            **opts,
2510        )
2511
2512    def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2513        """
2514        Append to or set the HAVING expressions.
2515
2516        Example:
2517            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2518            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2519
2520        Args:
2521            *expressions (str | Expression): the SQL code strings to parse.
2522                If an `Expression` instance is passed, it will be used as-is.
2523                Multiple expressions are combined with an AND operator.
2524            append (bool): if `True`, AND the new expressions to any existing expression.
2525                Otherwise, this resets the expression.
2526            dialect (str): the dialect used to parse the input expressions.
2527            copy (bool): if `False`, modify this expression instance in-place.
2528            opts (kwargs): other options to use to parse the input expressions.
2529
2530        Returns:
2531            Select: the modified expression.
2532        """
2533        return _apply_conjunction_builder(
2534            *expressions,
2535            instance=self,
2536            arg="having",
2537            append=append,
2538            into=Having,
2539            dialect=dialect,
2540            copy=copy,
2541            **opts,
2542        )
2543
2544    def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2545        return _apply_list_builder(
2546            *expressions,
2547            instance=self,
2548            arg="windows",
2549            append=append,
2550            into=Window,
2551            dialect=dialect,
2552            copy=copy,
2553            **opts,
2554        )
2555
2556    def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2557        return _apply_conjunction_builder(
2558            *expressions,
2559            instance=self,
2560            arg="qualify",
2561            append=append,
2562            into=Qualify,
2563            dialect=dialect,
2564            copy=copy,
2565            **opts,
2566        )
2567
2568    def distinct(self, distinct=True, copy=True) -> Select:
2569        """
2570        Set the OFFSET expression.
2571
2572        Example:
2573            >>> Select().from_("tbl").select("x").distinct().sql()
2574            'SELECT DISTINCT x FROM tbl'
2575
2576        Args:
2577            distinct (bool): whether the Select should be distinct
2578            copy (bool): if `False`, modify this expression instance in-place.
2579
2580        Returns:
2581            Select: the modified expression.
2582        """
2583        instance = _maybe_copy(self, copy)
2584        instance.set("distinct", Distinct() if distinct else None)
2585        return instance
2586
2587    def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create:
2588        """
2589        Convert this expression to a CREATE TABLE AS statement.
2590
2591        Example:
2592            >>> Select().select("*").from_("tbl").ctas("x").sql()
2593            'CREATE TABLE x AS SELECT * FROM tbl'
2594
2595        Args:
2596            table (str | Expression): the SQL code string to parse as the table name.
2597                If another `Expression` instance is passed, it will be used as-is.
2598            properties (dict): an optional mapping of table properties
2599            dialect (str): the dialect used to parse the input table.
2600            copy (bool): if `False`, modify this expression instance in-place.
2601            opts (kwargs): other options to use to parse the input table.
2602
2603        Returns:
2604            Create: the CREATE TABLE AS expression
2605        """
2606        instance = _maybe_copy(self, copy)
2607        table_expression = maybe_parse(
2608            table,
2609            into=Table,
2610            dialect=dialect,
2611            **opts,
2612        )
2613        properties_expression = None
2614        if properties:
2615            properties_expression = Properties.from_dict(properties)
2616
2617        return Create(
2618            this=table_expression,
2619            kind="table",
2620            expression=instance,
2621            properties=properties_expression,
2622        )
2623
2624    def lock(self, update: bool = True, copy: bool = True) -> Select:
2625        """
2626        Set the locking read mode for this expression.
2627
2628        Examples:
2629            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
2630            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
2631
2632            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
2633            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
2634
2635        Args:
2636            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
2637            copy: if `False`, modify this expression instance in-place.
2638
2639        Returns:
2640            The modified expression.
2641        """
2642
2643        inst = _maybe_copy(self, copy)
2644        inst.set("lock", Lock(update=update))
2645
2646        return inst
2647
2648    @property
2649    def named_selects(self) -> t.List[str]:
2650        return [e.output_name for e in self.expressions if e.alias_or_name]
2651
2652    @property
2653    def is_star(self) -> bool:
2654        return any(expression.is_star for expression in self.expressions)
2655
2656    @property
2657    def selects(self) -> t.List[Expression]:
2658        return self.expressions
def from_( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2086    def from_(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2087        """
2088        Set the FROM expression.
2089
2090        Example:
2091            >>> Select().from_("tbl").select("x").sql()
2092            'SELECT x FROM tbl'
2093
2094        Args:
2095            *expressions (str | Expression): the SQL code strings to parse.
2096                If a `From` instance is passed, this is used as-is.
2097                If another `Expression` instance is passed, it will be wrapped in a `From`.
2098            append (bool): if `True`, add to any existing expressions.
2099                Otherwise, this flattens all the `From` expression into a single expression.
2100            dialect (str): the dialect used to parse the input expression.
2101            copy (bool): if `False`, modify this expression instance in-place.
2102            opts (kwargs): other options to use to parse the input expressions.
2103
2104        Returns:
2105            Select: the modified expression.
2106        """
2107        return _apply_child_list_builder(
2108            *expressions,
2109            instance=self,
2110            arg="from",
2111            append=append,
2112            copy=copy,
2113            prefix="FROM",
2114            into=From,
2115            dialect=dialect,
2116            **opts,
2117        )

Set the FROM expression.

Example:
>>> Select().from_("tbl").select("x").sql()
'SELECT x FROM tbl'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If a From instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a From.
  • append (bool): if True, add to any existing expressions. Otherwise, this flattens all the From expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def group_by( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2119    def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2120        """
2121        Set the GROUP BY expression.
2122
2123        Example:
2124            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2125            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2126
2127        Args:
2128            *expressions (str | Expression): the SQL code strings to parse.
2129                If a `Group` instance is passed, this is used as-is.
2130                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2131                If nothing is passed in then a group by is not applied to the expression
2132            append (bool): if `True`, add to any existing expressions.
2133                Otherwise, this flattens all the `Group` expression into a single expression.
2134            dialect (str): the dialect used to parse the input expression.
2135            copy (bool): if `False`, modify this expression instance in-place.
2136            opts (kwargs): other options to use to parse the input expressions.
2137
2138        Returns:
2139            Select: the modified expression.
2140        """
2141        if not expressions:
2142            return self if not copy else self.copy()
2143        return _apply_child_list_builder(
2144            *expressions,
2145            instance=self,
2146            arg="group",
2147            append=append,
2148            copy=copy,
2149            prefix="GROUP BY",
2150            into=Group,
2151            dialect=dialect,
2152            **opts,
2153        )

Set the GROUP BY expression.

Example:
>>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
'SELECT x, COUNT(1) FROM tbl GROUP BY x'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Group. If nothing is passed in then a group by is not applied to the expression
  • append (bool): if True, add to any existing expressions. Otherwise, this flattens all the Group expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def order_by( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2155    def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2156        """
2157        Set the ORDER BY expression.
2158
2159        Example:
2160            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2161            'SELECT x FROM tbl ORDER BY x DESC'
2162
2163        Args:
2164            *expressions (str | Expression): the SQL code strings to parse.
2165                If a `Group` instance is passed, this is used as-is.
2166                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2167            append (bool): if `True`, add to any existing expressions.
2168                Otherwise, this flattens all the `Order` expression into a single expression.
2169            dialect (str): the dialect used to parse the input expression.
2170            copy (bool): if `False`, modify this expression instance in-place.
2171            opts (kwargs): other options to use to parse the input expressions.
2172
2173        Returns:
2174            Select: the modified expression.
2175        """
2176        return _apply_child_list_builder(
2177            *expressions,
2178            instance=self,
2179            arg="order",
2180            append=append,
2181            copy=copy,
2182            prefix="ORDER BY",
2183            into=Order,
2184            dialect=dialect,
2185            **opts,
2186        )

Set the ORDER BY expression.

Example:
>>> Select().from_("tbl").select("x").order_by("x DESC").sql()
'SELECT x FROM tbl ORDER BY x DESC'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Order.
  • append (bool): if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def sort_by( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2188    def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2189        """
2190        Set the SORT BY expression.
2191
2192        Example:
2193            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql()
2194            'SELECT x FROM tbl SORT BY x DESC'
2195
2196        Args:
2197            *expressions (str | Expression): the SQL code strings to parse.
2198                If a `Group` instance is passed, this is used as-is.
2199                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2200            append (bool): if `True`, add to any existing expressions.
2201                Otherwise, this flattens all the `Order` expression into a single expression.
2202            dialect (str): the dialect used to parse the input expression.
2203            copy (bool): if `False`, modify this expression instance in-place.
2204            opts (kwargs): other options to use to parse the input expressions.
2205
2206        Returns:
2207            Select: the modified expression.
2208        """
2209        return _apply_child_list_builder(
2210            *expressions,
2211            instance=self,
2212            arg="sort",
2213            append=append,
2214            copy=copy,
2215            prefix="SORT BY",
2216            into=Sort,
2217            dialect=dialect,
2218            **opts,
2219        )

Set the SORT BY expression.

Example:
>>> Select().from_("tbl").select("x").sort_by("x DESC").sql()
'SELECT x FROM tbl SORT BY x DESC'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a SORT.
  • append (bool): if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def cluster_by( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2221    def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2222        """
2223        Set the CLUSTER BY expression.
2224
2225        Example:
2226            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql()
2227            'SELECT x FROM tbl CLUSTER BY x DESC'
2228
2229        Args:
2230            *expressions (str | Expression): the SQL code strings to parse.
2231                If a `Group` instance is passed, this is used as-is.
2232                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2233            append (bool): if `True`, add to any existing expressions.
2234                Otherwise, this flattens all the `Order` expression into a single expression.
2235            dialect (str): the dialect used to parse the input expression.
2236            copy (bool): if `False`, modify this expression instance in-place.
2237            opts (kwargs): other options to use to parse the input expressions.
2238
2239        Returns:
2240            Select: the modified expression.
2241        """
2242        return _apply_child_list_builder(
2243            *expressions,
2244            instance=self,
2245            arg="cluster",
2246            append=append,
2247            copy=copy,
2248            prefix="CLUSTER BY",
2249            into=Cluster,
2250            dialect=dialect,
2251            **opts,
2252        )

Set the CLUSTER BY expression.

Example:
>>> Select().from_("tbl").select("x").cluster_by("x DESC").sql()
'SELECT x FROM tbl CLUSTER BY x DESC'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Cluster.
  • append (bool): if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def limit( self, expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2254    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2255        """
2256        Set the LIMIT expression.
2257
2258        Example:
2259            >>> Select().from_("tbl").select("x").limit(10).sql()
2260            'SELECT x FROM tbl LIMIT 10'
2261
2262        Args:
2263            expression (str | int | Expression): the SQL code string to parse.
2264                This can also be an integer.
2265                If a `Limit` instance is passed, this is used as-is.
2266                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2267            dialect (str): the dialect used to parse the input expression.
2268            copy (bool): if `False`, modify this expression instance in-place.
2269            opts (kwargs): other options to use to parse the input expressions.
2270
2271        Returns:
2272            Select: the modified expression.
2273        """
2274        return _apply_builder(
2275            expression=expression,
2276            instance=self,
2277            arg="limit",
2278            into=Limit,
2279            prefix="LIMIT",
2280            dialect=dialect,
2281            copy=copy,
2282            **opts,
2283        )

Set the LIMIT expression.

Example:
>>> Select().from_("tbl").select("x").limit(10).sql()
'SELECT x FROM tbl LIMIT 10'
Arguments:
  • expression (str | int | Expression): the SQL code string to parse. This can also be an integer. If a Limit instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Limit.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def offset( self, expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2285    def offset(self, expression, dialect=None, copy=True, **opts) -> Select:
2286        """
2287        Set the OFFSET expression.
2288
2289        Example:
2290            >>> Select().from_("tbl").select("x").offset(10).sql()
2291            'SELECT x FROM tbl OFFSET 10'
2292
2293        Args:
2294            expression (str | int | Expression): the SQL code string to parse.
2295                This can also be an integer.
2296                If a `Offset` instance is passed, this is used as-is.
2297                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2298            dialect (str): the dialect used to parse the input expression.
2299            copy (bool): if `False`, modify this expression instance in-place.
2300            opts (kwargs): other options to use to parse the input expressions.
2301
2302        Returns:
2303            Select: the modified expression.
2304        """
2305        return _apply_builder(
2306            expression=expression,
2307            instance=self,
2308            arg="offset",
2309            into=Offset,
2310            prefix="OFFSET",
2311            dialect=dialect,
2312            copy=copy,
2313            **opts,
2314        )

Set the OFFSET expression.

Example:
>>> Select().from_("tbl").select("x").offset(10).sql()
'SELECT x FROM tbl OFFSET 10'
Arguments:
  • expression (str | int | Expression): the SQL code string to parse. This can also be an integer. If a Offset instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Offset.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def select( self, *expressions: Union[str, sqlglot.expressions.Expression], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2316    def select(
2317        self,
2318        *expressions: ExpOrStr,
2319        append: bool = True,
2320        dialect: DialectType = None,
2321        copy: bool = True,
2322        **opts,
2323    ) -> Select:
2324        """
2325        Append to or set the SELECT expressions.
2326
2327        Example:
2328            >>> Select().select("x", "y").sql()
2329            'SELECT x, y'
2330
2331        Args:
2332            *expressions: the SQL code strings to parse.
2333                If an `Expression` instance is passed, it will be used as-is.
2334            append: if `True`, add to any existing expressions.
2335                Otherwise, this resets the expressions.
2336            dialect: the dialect used to parse the input expressions.
2337            copy: if `False`, modify this expression instance in-place.
2338            opts: other options to use to parse the input expressions.
2339
2340        Returns:
2341            Select: the modified expression.
2342        """
2343        return _apply_list_builder(
2344            *expressions,
2345            instance=self,
2346            arg="expressions",
2347            append=append,
2348            dialect=dialect,
2349            copy=copy,
2350            **opts,
2351        )

Append to or set the SELECT expressions.

Example:
>>> Select().select("x", "y").sql()
'SELECT x, y'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def lateral( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2353    def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2354        """
2355        Append to or set the LATERAL expressions.
2356
2357        Example:
2358            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2359            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2360
2361        Args:
2362            *expressions (str | Expression): the SQL code strings to parse.
2363                If an `Expression` instance is passed, it will be used as-is.
2364            append (bool): if `True`, add to any existing expressions.
2365                Otherwise, this resets the expressions.
2366            dialect (str): the dialect used to parse the input expressions.
2367            copy (bool): if `False`, modify this expression instance in-place.
2368            opts (kwargs): other options to use to parse the input expressions.
2369
2370        Returns:
2371            Select: the modified expression.
2372        """
2373        return _apply_list_builder(
2374            *expressions,
2375            instance=self,
2376            arg="laterals",
2377            append=append,
2378            into=Lateral,
2379            prefix="LATERAL VIEW",
2380            dialect=dialect,
2381            copy=copy,
2382            **opts,
2383        )

Append to or set the LATERAL expressions.

Example:
>>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append (bool): if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def join( self, expression, on=None, using=None, append=True, join_type=None, join_alias=None, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2385    def join(
2386        self,
2387        expression,
2388        on=None,
2389        using=None,
2390        append=True,
2391        join_type=None,
2392        join_alias=None,
2393        dialect=None,
2394        copy=True,
2395        **opts,
2396    ) -> Select:
2397        """
2398        Append to or set the JOIN expressions.
2399
2400        Example:
2401            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2402            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2403
2404            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2405            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2406
2407            Use `join_type` to change the type of join:
2408
2409            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2410            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2411
2412        Args:
2413            expression (str | Expression): the SQL code string to parse.
2414                If an `Expression` instance is passed, it will be used as-is.
2415            on (str | Expression): optionally specify the join "on" criteria as a SQL string.
2416                If an `Expression` instance is passed, it will be used as-is.
2417            using (str | Expression): optionally specify the join "using" criteria as a SQL string.
2418                If an `Expression` instance is passed, it will be used as-is.
2419            append (bool): if `True`, add to any existing expressions.
2420                Otherwise, this resets the expressions.
2421            join_type (str): If set, alter the parsed join type
2422            dialect (str): the dialect used to parse the input expressions.
2423            copy (bool): if `False`, modify this expression instance in-place.
2424            opts (kwargs): other options to use to parse the input expressions.
2425
2426        Returns:
2427            Select: the modified expression.
2428        """
2429        parse_args = {"dialect": dialect, **opts}
2430
2431        try:
2432            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2433        except ParseError:
2434            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2435
2436        join = expression if isinstance(expression, Join) else Join(this=expression)
2437
2438        if isinstance(join.this, Select):
2439            join.this.replace(join.this.subquery())
2440
2441        if join_type:
2442            natural: t.Optional[Token]
2443            side: t.Optional[Token]
2444            kind: t.Optional[Token]
2445
2446            natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2447
2448            if natural:
2449                join.set("natural", True)
2450            if side:
2451                join.set("side", side.text)
2452            if kind:
2453                join.set("kind", kind.text)
2454
2455        if on:
2456            on = and_(*ensure_collection(on), dialect=dialect, **opts)
2457            join.set("on", on)
2458
2459        if using:
2460            join = _apply_list_builder(
2461                *ensure_collection(using),
2462                instance=join,
2463                arg="using",
2464                append=append,
2465                copy=copy,
2466                **opts,
2467            )
2468
2469        if join_alias:
2470            join.set("this", alias_(join.this, join_alias, table=True))
2471        return _apply_list_builder(
2472            join,
2473            instance=self,
2474            arg="joins",
2475            append=append,
2476            copy=copy,
2477            **opts,
2478        )

Append to or set the JOIN expressions.

Example:
>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
>>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
'SELECT 1 FROM a JOIN b USING (x, y, z)'

Use join_type to change the type of join:

>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
Arguments:
  • expression (str | Expression): the SQL code string to parse. If an Expression instance is passed, it will be used as-is.
  • on (str | Expression): optionally specify the join "on" criteria as a SQL string. If an Expression instance is passed, it will be used as-is.
  • using (str | Expression): optionally specify the join "using" criteria as a SQL string. If an Expression instance is passed, it will be used as-is.
  • append (bool): if True, add to any existing expressions. Otherwise, this resets the expressions.
  • join_type (str): If set, alter the parsed join type
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def where( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2480    def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2481        """
2482        Append to or set the WHERE expressions.
2483
2484        Example:
2485            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2486            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2487
2488        Args:
2489            *expressions (str | Expression): the SQL code strings to parse.
2490                If an `Expression` instance is passed, it will be used as-is.
2491                Multiple expressions are combined with an AND operator.
2492            append (bool): if `True`, AND the new expressions to any existing expression.
2493                Otherwise, this resets the expression.
2494            dialect (str): the dialect used to parse the input expressions.
2495            copy (bool): if `False`, modify this expression instance in-place.
2496            opts (kwargs): other options to use to parse the input expressions.
2497
2498        Returns:
2499            Select: the modified expression.
2500        """
2501        return _apply_conjunction_builder(
2502            *expressions,
2503            instance=self,
2504            arg="where",
2505            append=append,
2506            into=Where,
2507            dialect=dialect,
2508            copy=copy,
2509            **opts,
2510        )

Append to or set the WHERE expressions.

Example:
>>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
"SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append (bool): if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def having( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2512    def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2513        """
2514        Append to or set the HAVING expressions.
2515
2516        Example:
2517            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2518            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2519
2520        Args:
2521            *expressions (str | Expression): the SQL code strings to parse.
2522                If an `Expression` instance is passed, it will be used as-is.
2523                Multiple expressions are combined with an AND operator.
2524            append (bool): if `True`, AND the new expressions to any existing expression.
2525                Otherwise, this resets the expression.
2526            dialect (str): the dialect used to parse the input expressions.
2527            copy (bool): if `False`, modify this expression instance in-place.
2528            opts (kwargs): other options to use to parse the input expressions.
2529
2530        Returns:
2531            Select: the modified expression.
2532        """
2533        return _apply_conjunction_builder(
2534            *expressions,
2535            instance=self,
2536            arg="having",
2537            append=append,
2538            into=Having,
2539            dialect=dialect,
2540            copy=copy,
2541            **opts,
2542        )

Append to or set the HAVING expressions.

Example:
>>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append (bool): if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def window( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2544    def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2545        return _apply_list_builder(
2546            *expressions,
2547            instance=self,
2548            arg="windows",
2549            append=append,
2550            into=Window,
2551            dialect=dialect,
2552            copy=copy,
2553            **opts,
2554        )
def qualify( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2556    def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2557        return _apply_conjunction_builder(
2558            *expressions,
2559            instance=self,
2560            arg="qualify",
2561            append=append,
2562            into=Qualify,
2563            dialect=dialect,
2564            copy=copy,
2565            **opts,
2566        )
def distinct(self, distinct=True, copy=True) -> sqlglot.expressions.Select:
2568    def distinct(self, distinct=True, copy=True) -> Select:
2569        """
2570        Set the OFFSET expression.
2571
2572        Example:
2573            >>> Select().from_("tbl").select("x").distinct().sql()
2574            'SELECT DISTINCT x FROM tbl'
2575
2576        Args:
2577            distinct (bool): whether the Select should be distinct
2578            copy (bool): if `False`, modify this expression instance in-place.
2579
2580        Returns:
2581            Select: the modified expression.
2582        """
2583        instance = _maybe_copy(self, copy)
2584        instance.set("distinct", Distinct() if distinct else None)
2585        return instance

Set the OFFSET expression.

Example:
>>> Select().from_("tbl").select("x").distinct().sql()
'SELECT DISTINCT x FROM tbl'
Arguments:
  • distinct (bool): whether the Select should be distinct
  • copy (bool): if False, modify this expression instance in-place.
Returns:

Select: the modified expression.

def ctas( self, table, properties=None, dialect=None, copy=True, **opts) -> sqlglot.expressions.Create:
2587    def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create:
2588        """
2589        Convert this expression to a CREATE TABLE AS statement.
2590
2591        Example:
2592            >>> Select().select("*").from_("tbl").ctas("x").sql()
2593            'CREATE TABLE x AS SELECT * FROM tbl'
2594
2595        Args:
2596            table (str | Expression): the SQL code string to parse as the table name.
2597                If another `Expression` instance is passed, it will be used as-is.
2598            properties (dict): an optional mapping of table properties
2599            dialect (str): the dialect used to parse the input table.
2600            copy (bool): if `False`, modify this expression instance in-place.
2601            opts (kwargs): other options to use to parse the input table.
2602
2603        Returns:
2604            Create: the CREATE TABLE AS expression
2605        """
2606        instance = _maybe_copy(self, copy)
2607        table_expression = maybe_parse(
2608            table,
2609            into=Table,
2610            dialect=dialect,
2611            **opts,
2612        )
2613        properties_expression = None
2614        if properties:
2615            properties_expression = Properties.from_dict(properties)
2616
2617        return Create(
2618            this=table_expression,
2619            kind="table",
2620            expression=instance,
2621            properties=properties_expression,
2622        )

Convert this expression to a CREATE TABLE AS statement.

Example:
>>> Select().select("*").from_("tbl").ctas("x").sql()
'CREATE TABLE x AS SELECT * FROM tbl'
Arguments:
  • table (str | Expression): the SQL code string to parse as the table name. If another Expression instance is passed, it will be used as-is.
  • properties (dict): an optional mapping of table properties
  • dialect (str): the dialect used to parse the input table.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input table.
Returns:

Create: the CREATE TABLE AS expression

def lock( self, update: bool = True, copy: bool = True) -> sqlglot.expressions.Select:
2624    def lock(self, update: bool = True, copy: bool = True) -> Select:
2625        """
2626        Set the locking read mode for this expression.
2627
2628        Examples:
2629            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
2630            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
2631
2632            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
2633            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
2634
2635        Args:
2636            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
2637            copy: if `False`, modify this expression instance in-place.
2638
2639        Returns:
2640            The modified expression.
2641        """
2642
2643        inst = _maybe_copy(self, copy)
2644        inst.set("lock", Lock(update=update))
2645
2646        return inst

Set the locking read mode for this expression.

Examples:
>>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
"SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
>>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
"SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
Arguments:
  • update: if True, the locking type will be FOR UPDATE, else it will be FOR SHARE.
  • copy: if False, modify this expression instance in-place.
Returns:

The modified expression.

is_star: bool

Checks whether an expression is a star.

class Subquery(DerivedTable, Unionable):
2661class Subquery(DerivedTable, Unionable):
2662    arg_types = {
2663        "this": True,
2664        "alias": False,
2665        "with": False,
2666        **QUERY_MODIFIERS,
2667    }
2668
2669    def unnest(self):
2670        """
2671        Returns the first non subquery.
2672        """
2673        expression = self
2674        while isinstance(expression, Subquery):
2675            expression = expression.this
2676        return expression
2677
2678    @property
2679    def is_star(self) -> bool:
2680        return self.this.is_star
2681
2682    @property
2683    def output_name(self):
2684        return self.alias
def unnest(self):
2669    def unnest(self):
2670        """
2671        Returns the first non subquery.
2672        """
2673        expression = self
2674        while isinstance(expression, Subquery):
2675            expression = expression.this
2676        return expression

Returns the first non subquery.

is_star: bool

Checks whether an expression is a star.

output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class TableSample(Expression):
2687class TableSample(Expression):
2688    arg_types = {
2689        "this": False,
2690        "method": False,
2691        "bucket_numerator": False,
2692        "bucket_denominator": False,
2693        "bucket_field": False,
2694        "percent": False,
2695        "rows": False,
2696        "size": False,
2697        "seed": False,
2698        "kind": False,
2699    }
class Tag(Expression):
2702class Tag(Expression):
2703    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
2704
2705    arg_types = {
2706        "this": False,
2707        "prefix": False,
2708        "postfix": False,
2709    }

Tags are used for generating arbitrary sql like SELECT x.

class Pivot(Expression):
2712class Pivot(Expression):
2713    arg_types = {
2714        "this": False,
2715        "alias": False,
2716        "expressions": True,
2717        "field": True,
2718        "unpivot": True,
2719    }
class Window(Expression):
2722class Window(Expression):
2723    arg_types = {
2724        "this": True,
2725        "partition_by": False,
2726        "order": False,
2727        "spec": False,
2728        "alias": False,
2729    }
class WindowSpec(Expression):
2732class WindowSpec(Expression):
2733    arg_types = {
2734        "kind": False,
2735        "start": False,
2736        "start_side": False,
2737        "end": False,
2738        "end_side": False,
2739    }
class Where(Expression):
2742class Where(Expression):
2743    pass
class Star(Expression):
2746class Star(Expression):
2747    arg_types = {"except": False, "replace": False}
2748
2749    @property
2750    def name(self) -> str:
2751        return "*"
2752
2753    @property
2754    def output_name(self):
2755        return self.name
output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class Parameter(Expression):
2758class Parameter(Expression):
2759    arg_types = {"this": True, "wrapped": False}
class SessionParameter(Expression):
2762class SessionParameter(Expression):
2763    arg_types = {"this": True, "kind": False}
class Placeholder(Expression):
2766class Placeholder(Expression):
2767    arg_types = {"this": False}
class Null(Condition):
2770class Null(Condition):
2771    arg_types: t.Dict[str, t.Any] = {}
2772
2773    @property
2774    def name(self) -> str:
2775        return "NULL"
class Boolean(Condition):
2778class Boolean(Condition):
2779    pass
class DataType(Expression):
2782class DataType(Expression):
2783    arg_types = {
2784        "this": True,
2785        "expressions": False,
2786        "nested": False,
2787        "values": False,
2788        "prefix": False,
2789    }
2790
2791    class Type(AutoName):
2792        CHAR = auto()
2793        NCHAR = auto()
2794        VARCHAR = auto()
2795        NVARCHAR = auto()
2796        TEXT = auto()
2797        MEDIUMTEXT = auto()
2798        LONGTEXT = auto()
2799        MEDIUMBLOB = auto()
2800        LONGBLOB = auto()
2801        BINARY = auto()
2802        VARBINARY = auto()
2803        INT = auto()
2804        UINT = auto()
2805        TINYINT = auto()
2806        UTINYINT = auto()
2807        SMALLINT = auto()
2808        USMALLINT = auto()
2809        BIGINT = auto()
2810        UBIGINT = auto()
2811        FLOAT = auto()
2812        DOUBLE = auto()
2813        DECIMAL = auto()
2814        BIT = auto()
2815        BOOLEAN = auto()
2816        JSON = auto()
2817        JSONB = auto()
2818        INTERVAL = auto()
2819        TIME = auto()
2820        TIMESTAMP = auto()
2821        TIMESTAMPTZ = auto()
2822        TIMESTAMPLTZ = auto()
2823        DATE = auto()
2824        DATETIME = auto()
2825        ARRAY = auto()
2826        MAP = auto()
2827        UUID = auto()
2828        GEOGRAPHY = auto()
2829        GEOMETRY = auto()
2830        STRUCT = auto()
2831        NULLABLE = auto()
2832        HLLSKETCH = auto()
2833        HSTORE = auto()
2834        SUPER = auto()
2835        SERIAL = auto()
2836        SMALLSERIAL = auto()
2837        BIGSERIAL = auto()
2838        XML = auto()
2839        UNIQUEIDENTIFIER = auto()
2840        MONEY = auto()
2841        SMALLMONEY = auto()
2842        ROWVERSION = auto()
2843        IMAGE = auto()
2844        VARIANT = auto()
2845        OBJECT = auto()
2846        INET = auto()
2847        NULL = auto()
2848        UNKNOWN = auto()  # Sentinel value, useful for type annotation
2849
2850    TEXT_TYPES = {
2851        Type.CHAR,
2852        Type.NCHAR,
2853        Type.VARCHAR,
2854        Type.NVARCHAR,
2855        Type.TEXT,
2856    }
2857
2858    INTEGER_TYPES = {
2859        Type.INT,
2860        Type.TINYINT,
2861        Type.SMALLINT,
2862        Type.BIGINT,
2863    }
2864
2865    FLOAT_TYPES = {
2866        Type.FLOAT,
2867        Type.DOUBLE,
2868    }
2869
2870    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
2871
2872    TEMPORAL_TYPES = {
2873        Type.TIMESTAMP,
2874        Type.TIMESTAMPTZ,
2875        Type.TIMESTAMPLTZ,
2876        Type.DATE,
2877        Type.DATETIME,
2878    }
2879
2880    @classmethod
2881    def build(
2882        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
2883    ) -> DataType:
2884        from sqlglot import parse_one
2885
2886        if isinstance(dtype, str):
2887            if dtype.upper() in cls.Type.__members__:
2888                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()])
2889            else:
2890                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
2891            if data_type_exp is None:
2892                raise ValueError(f"Unparsable data type value: {dtype}")
2893        elif isinstance(dtype, DataType.Type):
2894            data_type_exp = DataType(this=dtype)
2895        elif isinstance(dtype, DataType):
2896            return dtype
2897        else:
2898            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
2899        return DataType(**{**data_type_exp.args, **kwargs})
2900
2901    def is_type(self, dtype: DataType.Type) -> bool:
2902        return self.this == dtype
@classmethod
def build( cls, dtype: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> sqlglot.expressions.DataType:
2880    @classmethod
2881    def build(
2882        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
2883    ) -> DataType:
2884        from sqlglot import parse_one
2885
2886        if isinstance(dtype, str):
2887            if dtype.upper() in cls.Type.__members__:
2888                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()])
2889            else:
2890                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
2891            if data_type_exp is None:
2892                raise ValueError(f"Unparsable data type value: {dtype}")
2893        elif isinstance(dtype, DataType.Type):
2894            data_type_exp = DataType(this=dtype)
2895        elif isinstance(dtype, DataType):
2896            return dtype
2897        else:
2898            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
2899        return DataType(**{**data_type_exp.args, **kwargs})
def is_type(self, dtype: sqlglot.expressions.DataType.Type) -> bool:
2901    def is_type(self, dtype: DataType.Type) -> bool:
2902        return self.this == dtype
class DataType.Type(sqlglot.helper.AutoName):
2791    class Type(AutoName):
2792        CHAR = auto()
2793        NCHAR = auto()
2794        VARCHAR = auto()
2795        NVARCHAR = auto()
2796        TEXT = auto()
2797        MEDIUMTEXT = auto()
2798        LONGTEXT = auto()
2799        MEDIUMBLOB = auto()
2800        LONGBLOB = auto()
2801        BINARY = auto()
2802        VARBINARY = auto()
2803        INT = auto()
2804        UINT = auto()
2805        TINYINT = auto()
2806        UTINYINT = auto()
2807        SMALLINT = auto()
2808        USMALLINT = auto()
2809        BIGINT = auto()
2810        UBIGINT = auto()
2811        FLOAT = auto()
2812        DOUBLE = auto()
2813        DECIMAL = auto()
2814        BIT = auto()
2815        BOOLEAN = auto()
2816        JSON = auto()
2817        JSONB = auto()
2818        INTERVAL = auto()
2819        TIME = auto()
2820        TIMESTAMP = auto()
2821        TIMESTAMPTZ = auto()
2822        TIMESTAMPLTZ = auto()
2823        DATE = auto()
2824        DATETIME = auto()
2825        ARRAY = auto()
2826        MAP = auto()
2827        UUID = auto()
2828        GEOGRAPHY = auto()
2829        GEOMETRY = auto()
2830        STRUCT = auto()
2831        NULLABLE = auto()
2832        HLLSKETCH = auto()
2833        HSTORE = auto()
2834        SUPER = auto()
2835        SERIAL = auto()
2836        SMALLSERIAL = auto()
2837        BIGSERIAL = auto()
2838        XML = auto()
2839        UNIQUEIDENTIFIER = auto()
2840        MONEY = auto()
2841        SMALLMONEY = auto()
2842        ROWVERSION = auto()
2843        IMAGE = auto()
2844        VARIANT = auto()
2845        OBJECT = auto()
2846        INET = auto()
2847        NULL = auto()
2848        UNKNOWN = auto()  # Sentinel value, useful for type annotation

An enumeration.

CHAR = <Type.CHAR: 'CHAR'>
NCHAR = <Type.NCHAR: 'NCHAR'>
VARCHAR = <Type.VARCHAR: 'VARCHAR'>
NVARCHAR = <Type.NVARCHAR: 'NVARCHAR'>
TEXT = <Type.TEXT: 'TEXT'>
MEDIUMTEXT = <Type.MEDIUMTEXT: 'MEDIUMTEXT'>
LONGTEXT = <Type.LONGTEXT: 'LONGTEXT'>
MEDIUMBLOB = <Type.MEDIUMBLOB: 'MEDIUMBLOB'>
LONGBLOB = <Type.LONGBLOB: 'LONGBLOB'>
BINARY = <Type.BINARY: 'BINARY'>
VARBINARY = <Type.VARBINARY: 'VARBINARY'>
INT = <Type.INT: 'INT'>
UINT = <Type.UINT: 'UINT'>
TINYINT = <Type.TINYINT: 'TINYINT'>
UTINYINT = <Type.UTINYINT: 'UTINYINT'>
SMALLINT = <Type.SMALLINT: 'SMALLINT'>
USMALLINT = <Type.USMALLINT: 'USMALLINT'>
BIGINT = <Type.BIGINT: 'BIGINT'>
UBIGINT = <Type.UBIGINT: 'UBIGINT'>
FLOAT = <Type.FLOAT: 'FLOAT'>
DOUBLE = <Type.DOUBLE: 'DOUBLE'>
DECIMAL = <Type.DECIMAL: 'DECIMAL'>
BIT = <Type.BIT: 'BIT'>
BOOLEAN = <Type.BOOLEAN: 'BOOLEAN'>
JSON = <Type.JSON: 'JSON'>
JSONB = <Type.JSONB: 'JSONB'>
INTERVAL = <Type.INTERVAL: 'INTERVAL'>
TIME = <Type.TIME: 'TIME'>
TIMESTAMP = <Type.TIMESTAMP: 'TIMESTAMP'>
TIMESTAMPTZ = <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>
TIMESTAMPLTZ = <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>
DATE = <Type.DATE: 'DATE'>
DATETIME = <Type.DATETIME: 'DATETIME'>
ARRAY = <Type.ARRAY: 'ARRAY'>
MAP = <Type.MAP: 'MAP'>
UUID = <Type.UUID: 'UUID'>
GEOGRAPHY = <Type.GEOGRAPHY: 'GEOGRAPHY'>
GEOMETRY = <Type.GEOMETRY: 'GEOMETRY'>
STRUCT = <Type.STRUCT: 'STRUCT'>
NULLABLE = <Type.NULLABLE: 'NULLABLE'>
HLLSKETCH = <Type.HLLSKETCH: 'HLLSKETCH'>
HSTORE = <Type.HSTORE: 'HSTORE'>
SUPER = <Type.SUPER: 'SUPER'>
SERIAL = <Type.SERIAL: 'SERIAL'>
SMALLSERIAL = <Type.SMALLSERIAL: 'SMALLSERIAL'>
BIGSERIAL = <Type.BIGSERIAL: 'BIGSERIAL'>
XML = <Type.XML: 'XML'>
UNIQUEIDENTIFIER = <Type.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>
MONEY = <Type.MONEY: 'MONEY'>
SMALLMONEY = <Type.SMALLMONEY: 'SMALLMONEY'>
ROWVERSION = <Type.ROWVERSION: 'ROWVERSION'>
IMAGE = <Type.IMAGE: 'IMAGE'>
VARIANT = <Type.VARIANT: 'VARIANT'>
OBJECT = <Type.OBJECT: 'OBJECT'>
INET = <Type.INET: 'INET'>
NULL = <Type.NULL: 'NULL'>
UNKNOWN = <Type.UNKNOWN: 'UNKNOWN'>
Inherited Members
enum.Enum
name
value
class PseudoType(Expression):
2906class PseudoType(Expression):
2907    pass
class StructKwarg(Expression):
2910class StructKwarg(Expression):
2911    arg_types = {"this": True, "expression": True}
class SubqueryPredicate(Predicate):
2915class SubqueryPredicate(Predicate):
2916    pass
class All(SubqueryPredicate):
2919class All(SubqueryPredicate):
2920    pass
class Any(SubqueryPredicate):
2923class Any(SubqueryPredicate):
2924    pass
class Exists(SubqueryPredicate):
2927class Exists(SubqueryPredicate):
2928    pass
class Command(Expression):
2933class Command(Expression):
2934    arg_types = {"this": True, "expression": False}
class Transaction(Expression):
2937class Transaction(Expression):
2938    arg_types = {"this": False, "modes": False}
class Commit(Expression):
2941class Commit(Expression):
2942    arg_types = {"chain": False}
class Rollback(Expression):
2945class Rollback(Expression):
2946    arg_types = {"savepoint": False}
class AlterTable(Expression):
2949class AlterTable(Expression):
2950    arg_types = {"this": True, "actions": True, "exists": False}
class AddConstraint(Expression):
2953class AddConstraint(Expression):
2954    arg_types = {"this": False, "expression": False, "enforced": False}
class DropPartition(Expression):
2957class DropPartition(Expression):
2958    arg_types = {"expressions": True, "exists": False}
class Binary(Expression):
2962class Binary(Expression):
2963    arg_types = {"this": True, "expression": True}
2964
2965    @property
2966    def left(self):
2967        return self.this
2968
2969    @property
2970    def right(self):
2971        return self.expression
class Add(Binary):
2974class Add(Binary):
2975    pass
class Connector(Binary, Condition):
2978class Connector(Binary, Condition):
2979    pass
class And(Connector):
2982class And(Connector):
2983    pass
class Or(Connector):
2986class Or(Connector):
2987    pass
class BitwiseAnd(Binary):
2990class BitwiseAnd(Binary):
2991    pass
class BitwiseLeftShift(Binary):
2994class BitwiseLeftShift(Binary):
2995    pass
class BitwiseOr(Binary):
2998class BitwiseOr(Binary):
2999    pass
class BitwiseRightShift(Binary):
3002class BitwiseRightShift(Binary):
3003    pass
class BitwiseXor(Binary):
3006class BitwiseXor(Binary):
3007    pass
class Div(Binary):
3010class Div(Binary):
3011    pass
class Overlaps(Binary):
3014class Overlaps(Binary):
3015    pass
class Dot(Binary):
3018class Dot(Binary):
3019    @property
3020    def name(self) -> str:
3021        return self.expression.name
3022
3023    @classmethod
3024    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3025        """Build a Dot object with a sequence of expressions."""
3026        if len(expressions) < 2:
3027            raise ValueError(f"Dot requires >= 2 expressions.")
3028
3029        a, b, *expressions = expressions
3030        dot = Dot(this=a, expression=b)
3031
3032        for expression in expressions:
3033            dot = Dot(this=dot, expression=expression)
3034
3035        return dot
@classmethod
def build( self, expressions: Sequence[sqlglot.expressions.Expression]) -> sqlglot.expressions.Dot:
3023    @classmethod
3024    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3025        """Build a Dot object with a sequence of expressions."""
3026        if len(expressions) < 2:
3027            raise ValueError(f"Dot requires >= 2 expressions.")
3028
3029        a, b, *expressions = expressions
3030        dot = Dot(this=a, expression=b)
3031
3032        for expression in expressions:
3033            dot = Dot(this=dot, expression=expression)
3034
3035        return dot

Build a Dot object with a sequence of expressions.

class DPipe(Binary):
3038class DPipe(Binary):
3039    pass
class EQ(Binary, Predicate):
3042class EQ(Binary, Predicate):
3043    pass
class NullSafeEQ(Binary, Predicate):
3046class NullSafeEQ(Binary, Predicate):
3047    pass
class NullSafeNEQ(Binary, Predicate):
3050class NullSafeNEQ(Binary, Predicate):
3051    pass
class Distance(Binary):
3054class Distance(Binary):
3055    pass
class Escape(Binary):
3058class Escape(Binary):
3059    pass
class Glob(Binary, Predicate):
3062class Glob(Binary, Predicate):
3063    pass
class GT(Binary, Predicate):
3066class GT(Binary, Predicate):
3067    pass
class GTE(Binary, Predicate):
3070class GTE(Binary, Predicate):
3071    pass
class ILike(Binary, Predicate):
3074class ILike(Binary, Predicate):
3075    pass
class ILikeAny(Binary, Predicate):
3078class ILikeAny(Binary, Predicate):
3079    pass
class IntDiv(Binary):
3082class IntDiv(Binary):
3083    pass
class Is(Binary, Predicate):
3086class Is(Binary, Predicate):
3087    pass
class Kwarg(Binary):
3090class Kwarg(Binary):
3091    """Kwarg in special functions like func(kwarg => y)."""

Kwarg in special functions like func(kwarg => y).

class Like(Binary, Predicate):
3094class Like(Binary, Predicate):
3095    pass
class LikeAny(Binary, Predicate):
3098class LikeAny(Binary, Predicate):
3099    pass
class LT(Binary, Predicate):
3102class LT(Binary, Predicate):
3103    pass
class LTE(Binary, Predicate):
3106class LTE(Binary, Predicate):
3107    pass
class Mod(Binary):
3110class Mod(Binary):
3111    pass
class Mul(Binary):
3114class Mul(Binary):
3115    pass
class NEQ(Binary, Predicate):
3118class NEQ(Binary, Predicate):
3119    pass
class SimilarTo(Binary, Predicate):
3122class SimilarTo(Binary, Predicate):
3123    pass
class Slice(Binary):
3126class Slice(Binary):
3127    arg_types = {"this": False, "expression": False}
class Sub(Binary):
3130class Sub(Binary):
3131    pass
class ArrayOverlaps(Binary):
3134class ArrayOverlaps(Binary):
3135    pass
class Unary(Expression):
3140class Unary(Expression):
3141    pass
class BitwiseNot(Unary):
3144class BitwiseNot(Unary):
3145    pass
class Not(Unary, Condition):
3148class Not(Unary, Condition):
3149    pass
class Paren(Unary, Condition):
3152class Paren(Unary, Condition):
3153    arg_types = {"this": True, "with": False}
class Neg(Unary):
3156class Neg(Unary):
3157    pass
class Alias(Expression):
3161class Alias(Expression):
3162    arg_types = {"this": True, "alias": False}
3163
3164    @property
3165    def output_name(self):
3166        return self.alias
output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class Aliases(Expression):
3169class Aliases(Expression):
3170    arg_types = {"this": True, "expressions": True}
3171
3172    @property
3173    def aliases(self):
3174        return self.expressions
class AtTimeZone(Expression):
3177class AtTimeZone(Expression):
3178    arg_types = {"this": True, "zone": True}
class Between(Predicate):
3181class Between(Predicate):
3182    arg_types = {"this": True, "low": True, "high": True}
class Bracket(Condition):
3185class Bracket(Condition):
3186    arg_types = {"this": True, "expressions": True}
class Distinct(Expression):
3189class Distinct(Expression):
3190    arg_types = {"expressions": False, "on": False}
class In(Predicate):
3193class In(Predicate):
3194    arg_types = {
3195        "this": True,
3196        "expressions": False,
3197        "query": False,
3198        "unnest": False,
3199        "field": False,
3200        "is_global": False,
3201    }
class TimeUnit(Expression):
3204class TimeUnit(Expression):
3205    """Automatically converts unit arg into a var."""
3206
3207    arg_types = {"unit": False}
3208
3209    def __init__(self, **args):
3210        unit = args.get("unit")
3211        if isinstance(unit, (Column, Literal)):
3212            args["unit"] = Var(this=unit.name)
3213        elif isinstance(unit, Week):
3214            unit.set("this", Var(this=unit.this.name))
3215        super().__init__(**args)

Automatically converts unit arg into a var.

TimeUnit(**args)
3209    def __init__(self, **args):
3210        unit = args.get("unit")
3211        if isinstance(unit, (Column, Literal)):
3212            args["unit"] = Var(this=unit.name)
3213        elif isinstance(unit, Week):
3214            unit.set("this", Var(this=unit.this.name))
3215        super().__init__(**args)
class Interval(TimeUnit):
3218class Interval(TimeUnit):
3219    arg_types = {"this": False, "unit": False}
class IgnoreNulls(Expression):
3222class IgnoreNulls(Expression):
3223    pass
class RespectNulls(Expression):
3226class RespectNulls(Expression):
3227    pass
class Func(Condition):
3231class Func(Condition):
3232    """
3233    The base class for all function expressions.
3234
3235    Attributes:
3236        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3237            treated as a variable length argument and the argument's value will be stored as a list.
3238        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3239            for this function expression. These values are used to map this node to a name during parsing
3240            as well as to provide the function's name during SQL string generation. By default the SQL
3241            name is set to the expression's class name transformed to snake case.
3242    """
3243
3244    is_var_len_args = False
3245
3246    @classmethod
3247    def from_arg_list(cls, args):
3248        if cls.is_var_len_args:
3249            all_arg_keys = list(cls.arg_types)
3250            # If this function supports variable length argument treat the last argument as such.
3251            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3252            num_non_var = len(non_var_len_arg_keys)
3253
3254            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3255            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3256        else:
3257            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3258
3259        return cls(**args_dict)
3260
3261    @classmethod
3262    def sql_names(cls):
3263        if cls is Func:
3264            raise NotImplementedError(
3265                "SQL name is only supported by concrete function implementations"
3266            )
3267        if "_sql_names" not in cls.__dict__:
3268            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3269        return cls._sql_names
3270
3271    @classmethod
3272    def sql_name(cls):
3273        return cls.sql_names()[0]
3274
3275    @classmethod
3276    def default_parser_mappings(cls):
3277        return {name: cls.from_arg_list for name in cls.sql_names()}

The base class for all function expressions.

Attributes:
  • is_var_len_args (bool): if set to True the last argument defined in arg_types will be treated as a variable length argument and the argument's value will be stored as a list.
  • _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items) for this function expression. These values are used to map this node to a name during parsing as well as to provide the function's name during SQL string generation. By default the SQL name is set to the expression's class name transformed to snake case.
@classmethod
def from_arg_list(cls, args):
3246    @classmethod
3247    def from_arg_list(cls, args):
3248        if cls.is_var_len_args:
3249            all_arg_keys = list(cls.arg_types)
3250            # If this function supports variable length argument treat the last argument as such.
3251            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3252            num_non_var = len(non_var_len_arg_keys)
3253
3254            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3255            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3256        else:
3257            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3258
3259        return cls(**args_dict)
@classmethod
def sql_names(cls):
3261    @classmethod
3262    def sql_names(cls):
3263        if cls is Func:
3264            raise NotImplementedError(
3265                "SQL name is only supported by concrete function implementations"
3266            )
3267        if "_sql_names" not in cls.__dict__:
3268            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3269        return cls._sql_names
@classmethod
def sql_name(cls):
3271    @classmethod
3272    def sql_name(cls):
3273        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
3275    @classmethod
3276    def default_parser_mappings(cls):
3277        return {name: cls.from_arg_list for name in cls.sql_names()}
class AggFunc(Func):
3280class AggFunc(Func):
3281    pass
class Abs(Func):
3284class Abs(Func):
3285    pass
class Anonymous(Func):
3288class Anonymous(Func):
3289    arg_types = {"this": True, "expressions": False}
3290    is_var_len_args = True
class ApproxDistinct(AggFunc):
3293class ApproxDistinct(AggFunc):
3294    arg_types = {"this": True, "accuracy": False}
class Array(Func):
3297class Array(Func):
3298    arg_types = {"expressions": False}
3299    is_var_len_args = True
class ToChar(Func):
3303class ToChar(Func):
3304    arg_types = {"this": True, "format": False}
class GenerateSeries(Func):
3307class GenerateSeries(Func):
3308    arg_types = {"start": True, "end": True, "step": False}
class ArrayAgg(AggFunc):
3311class ArrayAgg(AggFunc):
3312    pass
class ArrayAll(Func):
3315class ArrayAll(Func):
3316    arg_types = {"this": True, "expression": True}
class ArrayAny(Func):
3319class ArrayAny(Func):
3320    arg_types = {"this": True, "expression": True}
class ArrayConcat(Func):
3323class ArrayConcat(Func):
3324    arg_types = {"this": True, "expressions": False}
3325    is_var_len_args = True
class ArrayContains(Binary, Func):
3328class ArrayContains(Binary, Func):
3329    pass
class ArrayContained(Binary):
3332class ArrayContained(Binary):
3333    pass
class ArrayFilter(Func):
3336class ArrayFilter(Func):
3337    arg_types = {"this": True, "expression": True}
3338    _sql_names = ["FILTER", "ARRAY_FILTER"]
class ArrayJoin(Func):
3341class ArrayJoin(Func):
3342    arg_types = {"this": True, "expression": True, "null": False}
class ArraySize(Func):
3345class ArraySize(Func):
3346    arg_types = {"this": True, "expression": False}
class ArraySort(Func):
3349class ArraySort(Func):
3350    arg_types = {"this": True, "expression": False}
class ArraySum(Func):
3353class ArraySum(Func):
3354    pass
class ArrayUnionAgg(AggFunc):
3357class ArrayUnionAgg(AggFunc):
3358    pass
class Avg(AggFunc):
3361class Avg(AggFunc):
3362    pass
class AnyValue(AggFunc):
3365class AnyValue(AggFunc):
3366    pass
class Case(Func):
3369class Case(Func):
3370    arg_types = {"this": False, "ifs": True, "default": False}
class Cast(Func):
3373class Cast(Func):
3374    arg_types = {"this": True, "to": True}
3375
3376    @property
3377    def name(self) -> str:
3378        return self.this.name
3379
3380    @property
3381    def to(self):
3382        return self.args["to"]
3383
3384    @property
3385    def output_name(self):
3386        return self.name
3387
3388    def is_type(self, dtype: DataType.Type) -> bool:
3389        return self.to.is_type(dtype)
output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
def is_type(self, dtype: sqlglot.expressions.DataType.Type) -> bool:
3388    def is_type(self, dtype: DataType.Type) -> bool:
3389        return self.to.is_type(dtype)
class Collate(Binary):
3392class Collate(Binary):
3393    pass
class TryCast(Cast):
3396class TryCast(Cast):
3397    pass
class Ceil(Func):
3400class Ceil(Func):
3401    arg_types = {"this": True, "decimals": False}
3402    _sql_names = ["CEIL", "CEILING"]
class Coalesce(Func):
3405class Coalesce(Func):
3406    arg_types = {"this": True, "expressions": False}
3407    is_var_len_args = True
class Concat(Func):
3410class Concat(Func):
3411    arg_types = {"expressions": True}
3412    is_var_len_args = True
class ConcatWs(Concat):
3415class ConcatWs(Concat):
3416    _sql_names = ["CONCAT_WS"]
class Count(AggFunc):
3419class Count(AggFunc):
3420    arg_types = {"this": False}
class CountIf(AggFunc):
3423class CountIf(AggFunc):
3424    pass
class CurrentDate(Func):
3427class CurrentDate(Func):
3428    arg_types = {"this": False}
class CurrentDatetime(Func):
3431class CurrentDatetime(Func):
3432    arg_types = {"this": False}
class CurrentTime(Func):
3435class CurrentTime(Func):
3436    arg_types = {"this": False}
class CurrentTimestamp(Func):
3439class CurrentTimestamp(Func):
3440    arg_types = {"this": False}
class DateAdd(Func, TimeUnit):
3443class DateAdd(Func, TimeUnit):
3444    arg_types = {"this": True, "expression": True, "unit": False}
class DateSub(Func, TimeUnit):
3447class DateSub(Func, TimeUnit):
3448    arg_types = {"this": True, "expression": True, "unit": False}
class DateDiff(Func, TimeUnit):
3451class DateDiff(Func, TimeUnit):
3452    _sql_names = ["DATEDIFF", "DATE_DIFF"]
3453    arg_types = {"this": True, "expression": True, "unit": False}
class DateTrunc(Func):
3456class DateTrunc(Func):
3457    arg_types = {"unit": True, "this": True, "zone": False}
class DatetimeAdd(Func, TimeUnit):
3460class DatetimeAdd(Func, TimeUnit):
3461    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeSub(Func, TimeUnit):
3464class DatetimeSub(Func, TimeUnit):
3465    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeDiff(Func, TimeUnit):
3468class DatetimeDiff(Func, TimeUnit):
3469    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeTrunc(Func, TimeUnit):
3472class DatetimeTrunc(Func, TimeUnit):
3473    arg_types = {"this": True, "unit": True, "zone": False}
class DayOfWeek(Func):
3476class DayOfWeek(Func):
3477    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
class DayOfMonth(Func):
3480class DayOfMonth(Func):
3481    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
class DayOfYear(Func):
3484class DayOfYear(Func):
3485    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
class WeekOfYear(Func):
3488class WeekOfYear(Func):
3489    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
class LastDateOfMonth(Func):
3492class LastDateOfMonth(Func):
3493    pass
class Extract(Func):
3496class Extract(Func):
3497    arg_types = {"this": True, "expression": True}
class TimestampAdd(Func, TimeUnit):
3500class TimestampAdd(Func, TimeUnit):
3501    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampSub(Func, TimeUnit):
3504class TimestampSub(Func, TimeUnit):
3505    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampDiff(Func, TimeUnit):
3508class TimestampDiff(Func, TimeUnit):
3509    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampTrunc(Func, TimeUnit):
3512class TimestampTrunc(Func, TimeUnit):
3513    arg_types = {"this": True, "unit": True, "zone": False}
class TimeAdd(Func, TimeUnit):
3516class TimeAdd(Func, TimeUnit):
3517    arg_types = {"this": True, "expression": True, "unit": False}
class TimeSub(Func, TimeUnit):
3520class TimeSub(Func, TimeUnit):
3521    arg_types = {"this": True, "expression": True, "unit": False}
class TimeDiff(Func, TimeUnit):
3524class TimeDiff(Func, TimeUnit):
3525    arg_types = {"this": True, "expression": True, "unit": False}
class TimeTrunc(Func, TimeUnit):
3528class TimeTrunc(Func, TimeUnit):
3529    arg_types = {"this": True, "unit": True, "zone": False}
class DateFromParts(Func):
3532class DateFromParts(Func):
3533    _sql_names = ["DATEFROMPARTS"]
3534    arg_types = {"year": True, "month": True, "day": True}
class DateStrToDate(Func):
3537class DateStrToDate(Func):
3538    pass
class DateToDateStr(Func):
3541class DateToDateStr(Func):
3542    pass
class DateToDi(Func):
3545class DateToDi(Func):
3546    pass
class Day(Func):
3549class Day(Func):
3550    pass
class Decode(Func):
3553class Decode(Func):
3554    arg_types = {"this": True, "charset": True, "replace": False}
class DiToDate(Func):
3557class DiToDate(Func):
3558    pass
class Encode(Func):
3561class Encode(Func):
3562    arg_types = {"this": True, "charset": True}
class Exp(Func):
3565class Exp(Func):
3566    pass
class Explode(Func):
3569class Explode(Func):
3570    pass
class ExponentialTimeDecayedAvg(AggFunc):
3573class ExponentialTimeDecayedAvg(AggFunc):
3574    arg_types = {"this": True, "time": False, "decay": False}
class Floor(Func):
3577class Floor(Func):
3578    arg_types = {"this": True, "decimals": False}
class Greatest(Func):
3581class Greatest(Func):
3582    arg_types = {"this": True, "expressions": False}
3583    is_var_len_args = True
class GroupConcat(Func):
3586class GroupConcat(Func):
3587    arg_types = {"this": True, "separator": False}
class GroupUniqArray(AggFunc):
3590class GroupUniqArray(AggFunc):
3591    arg_types = {"this": True, "size": False}
class Hex(Func):
3594class Hex(Func):
3595    pass
class Histogram(AggFunc):
3598class Histogram(AggFunc):
3599    arg_types = {"this": True, "bins": False}
class If(Func):
3602class If(Func):
3603    arg_types = {"this": True, "true": True, "false": False}
class IfNull(Func):
3606class IfNull(Func):
3607    arg_types = {"this": True, "expression": False}
3608    _sql_names = ["IFNULL", "NVL"]
class Initcap(Func):
3611class Initcap(Func):
3612    pass
class JSONBContains(Binary):
3615class JSONBContains(Binary):
3616    _sql_names = ["JSONB_CONTAINS"]
class JSONExtract(Binary, Func):
3619class JSONExtract(Binary, Func):
3620    _sql_names = ["JSON_EXTRACT"]
class JSONExtractScalar(JSONExtract):
3623class JSONExtractScalar(JSONExtract):
3624    _sql_names = ["JSON_EXTRACT_SCALAR"]
class JSONBExtract(JSONExtract):
3627class JSONBExtract(JSONExtract):
3628    _sql_names = ["JSONB_EXTRACT"]
class JSONBExtractScalar(JSONExtract):
3631class JSONBExtractScalar(JSONExtract):
3632    _sql_names = ["JSONB_EXTRACT_SCALAR"]
class Least(Func):
3635class Least(Func):
3636    arg_types = {"expressions": False}
3637    is_var_len_args = True
class Length(Func):
3640class Length(Func):
3641    pass
class Levenshtein(Func):
3644class Levenshtein(Func):
3645    arg_types = {
3646        "this": True,
3647        "expression": False,
3648        "ins_cost": False,
3649        "del_cost": False,
3650        "sub_cost": False,
3651    }
class Ln(Func):
3654class Ln(Func):
3655    pass
class Log(Func):
3658class Log(Func):
3659    arg_types = {"this": True, "expression": False}
class Log2(Func):
3662class Log2(Func):
3663    pass
class Log10(Func):
3666class Log10(Func):
3667    pass
class LogicalOr(AggFunc):
3670class LogicalOr(AggFunc):
3671    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
class LogicalAnd(AggFunc):
3674class LogicalAnd(AggFunc):
3675    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
class Lower(Func):
3678class Lower(Func):
3679    _sql_names = ["LOWER", "LCASE"]
class Map(Func):
3682class Map(Func):
3683    arg_types = {"keys": False, "values": False}
class VarMap(Func):
3686class VarMap(Func):
3687    arg_types = {"keys": True, "values": True}
3688    is_var_len_args = True
class Matches(Func):
3691class Matches(Func):
3692    """Oracle/Snowflake decode.
3693    https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions040.htm
3694    Pattern matching MATCHES(value, search1, result1, ...searchN, resultN, else)
3695    """
3696
3697    arg_types = {"this": True, "expressions": True}
3698    is_var_len_args = True

Oracle/Snowflake decode. https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions040.htm Pattern matching MATCHES(value, search1, result1, ...searchN, resultN, else)

class Max(AggFunc):
3701class Max(AggFunc):
3702    arg_types = {"this": True, "expressions": False}
3703    is_var_len_args = True
class Min(AggFunc):
3706class Min(AggFunc):
3707    arg_types = {"this": True, "expressions": False}
3708    is_var_len_args = True
class Month(Func):
3711class Month(Func):
3712    pass
class Nvl2(Func):
3715class Nvl2(Func):
3716    arg_types = {"this": True, "true": True, "false": False}
class Posexplode(Func):
3719class Posexplode(Func):
3720    pass
class Pow(Binary, Func):
3723class Pow(Binary, Func):
3724    _sql_names = ["POWER", "POW"]
class PercentileCont(AggFunc):
3727class PercentileCont(AggFunc):
3728    pass
class PercentileDisc(AggFunc):
3731class PercentileDisc(AggFunc):
3732    pass
class Quantile(AggFunc):
3735class Quantile(AggFunc):
3736    arg_types = {"this": True, "quantile": True}
class Quantiles(AggFunc):
3741class Quantiles(AggFunc):
3742    arg_types = {"parameters": True, "expressions": True}
3743    is_var_len_args = True
class QuantileIf(AggFunc):
3746class QuantileIf(AggFunc):
3747    arg_types = {"parameters": True, "expressions": True}
class ApproxQuantile(Quantile):
3750class ApproxQuantile(Quantile):
3751    arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
class RangeN(Func):
3754class RangeN(Func):
3755    arg_types = {"this": True, "expressions": True, "each": False}
class ReadCSV(Func):
3758class ReadCSV(Func):
3759    _sql_names = ["READ_CSV"]
3760    is_var_len_args = True
3761    arg_types = {"this": True, "expressions": False}
class Reduce(Func):
3764class Reduce(Func):
3765    arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
class RegexpExtract(Func):
3768class RegexpExtract(Func):
3769    arg_types = {
3770        "this": True,
3771        "expression": True,
3772        "position": False,
3773        "occurrence": False,
3774        "group": False,
3775    }
class RegexpLike(Func):
3778class RegexpLike(Func):
3779    arg_types = {"this": True, "expression": True, "flag": False}
class RegexpILike(Func):
3782class RegexpILike(Func):
3783    arg_types = {"this": True, "expression": True, "flag": False}
class RegexpSplit(Func):
3786class RegexpSplit(Func):
3787    arg_types = {"this": True, "expression": True}
class Repeat(Func):
3790class Repeat(Func):
3791    arg_types = {"this": True, "times": True}
class Round(Func):
3794class Round(Func):
3795    arg_types = {"this": True, "decimals": False}
class RowNumber(Func):
3798class RowNumber(Func):
3799    arg_types: t.Dict[str, t.Any] = {}
class SafeDivide(Func):
3802class SafeDivide(Func):
3803    arg_types = {"this": True, "expression": True}
class SetAgg(AggFunc):
3806class SetAgg(AggFunc):
3807    pass
class SortArray(Func):
3810class SortArray(Func):
3811    arg_types = {"this": True, "asc": False}
class Split(Func):
3814class Split(Func):
3815    arg_types = {"this": True, "expression": True, "limit": False}
class Substring(Func):
3820class Substring(Func):
3821    arg_types = {"this": True, "start": False, "length": False}
class StrPosition(Func):
3824class StrPosition(Func):
3825    arg_types = {
3826        "this": True,
3827        "substr": True,
3828        "position": False,
3829        "instance": False,
3830    }
class StrToDate(Func):
3833class StrToDate(Func):
3834    arg_types = {"this": True, "format": True}
class StrToTime(Func):
3837class StrToTime(Func):
3838    arg_types = {"this": True, "format": True}
class StrToUnix(Func):
3843class StrToUnix(Func):
3844    arg_types = {"this": False, "format": False}
class NumberToStr(Func):
3847class NumberToStr(Func):
3848    arg_types = {"this": True, "format": True}
class Struct(Func):
3851class Struct(Func):
3852    arg_types = {"expressions": True}
3853    is_var_len_args = True
class StructExtract(Func):
3856class StructExtract(Func):
3857    arg_types = {"this": True, "expression": True}
class Sum(AggFunc):
3860class Sum(AggFunc):
3861    pass
class Sqrt(Func):
3864class Sqrt(Func):
3865    pass
class Stddev(AggFunc):
3868class Stddev(AggFunc):
3869    pass
class StddevPop(AggFunc):
3872class StddevPop(AggFunc):
3873    pass
class StddevSamp(AggFunc):
3876class StddevSamp(AggFunc):
3877    pass
class TimeToStr(Func):
3880class TimeToStr(Func):
3881    arg_types = {"this": True, "format": True}
class TimeToTimeStr(Func):
3884class TimeToTimeStr(Func):
3885    pass
class TimeToUnix(Func):
3888class TimeToUnix(Func):
3889    pass
class TimeStrToDate(Func):
3892class TimeStrToDate(Func):
3893    pass
class TimeStrToTime(Func):
3896class TimeStrToTime(Func):
3897    pass
class TimeStrToUnix(Func):
3900class TimeStrToUnix(Func):
3901    pass
class Trim(Func):
3904class Trim(Func):
3905    arg_types = {
3906        "this": True,
3907        "expression": False,
3908        "position": False,
3909        "collation": False,
3910    }
class TsOrDsAdd(Func, TimeUnit):
3913class TsOrDsAdd(Func, TimeUnit):
3914    arg_types = {"this": True, "expression": True, "unit": False}
class TsOrDsToDateStr(Func):
3917class TsOrDsToDateStr(Func):
3918    pass
class TsOrDsToDate(Func):
3921class TsOrDsToDate(Func):
3922    arg_types = {"this": True, "format": False}
class TsOrDiToDi(Func):
3925class TsOrDiToDi(Func):
3926    pass
class Unhex(Func):
3929class Unhex(Func):
3930    pass
class UnixToStr(Func):
3933class UnixToStr(Func):
3934    arg_types = {"this": True, "format": False}
class UnixToTime(Func):
3939class UnixToTime(Func):
3940    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
3941
3942    SECONDS = Literal.string("seconds")
3943    MILLIS = Literal.string("millis")
3944    MICROS = Literal.string("micros")
class UnixToTimeStr(Func):
3947class UnixToTimeStr(Func):
3948    pass
class Upper(Func):
3951class Upper(Func):
3952    _sql_names = ["UPPER", "UCASE"]
class Variance(AggFunc):
3955class Variance(AggFunc):
3956    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
class VariancePop(AggFunc):
3959class VariancePop(AggFunc):
3960    _sql_names = ["VARIANCE_POP", "VAR_POP"]
class Week(Func):
3963class Week(Func):
3964    arg_types = {"this": True, "mode": False}
class XMLTable(Func):
3967class XMLTable(Func):
3968    arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
class Year(Func):
3971class Year(Func):
3972    pass
class Use(Expression):
3975class Use(Expression):
3976    arg_types = {"this": True, "kind": False}
class Merge(Expression):
3979class Merge(Expression):
3980    arg_types = {"this": True, "using": True, "on": True, "expressions": True}
class When(Func):
3983class When(Func):
3984    arg_types = {"matched": True, "source": False, "condition": False, "then": True}
def maybe_parse( sql_or_expression: Union[str, sqlglot.expressions.Expression], *, into: Union[str, Type[sqlglot.expressions.Expression], Collection[Union[str, Type[sqlglot.expressions.Expression]]], NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, prefix: Optional[str] = None, copy: bool = False, **opts) -> sqlglot.expressions.Expression:
3995def maybe_parse(
3996    sql_or_expression: ExpOrStr,
3997    *,
3998    into: t.Optional[IntoType] = None,
3999    dialect: DialectType = None,
4000    prefix: t.Optional[str] = None,
4001    copy: bool = False,
4002    **opts,
4003) -> Expression:
4004    """Gracefully handle a possible string or expression.
4005
4006    Example:
4007        >>> maybe_parse("1")
4008        (LITERAL this: 1, is_string: False)
4009        >>> maybe_parse(to_identifier("x"))
4010        (IDENTIFIER this: x, quoted: False)
4011
4012    Args:
4013        sql_or_expression: the SQL code string or an expression
4014        into: the SQLGlot Expression to parse into
4015        dialect: the dialect used to parse the input expressions (in the case that an
4016            input expression is a SQL string).
4017        prefix: a string to prefix the sql with before it gets parsed
4018            (automatically includes a space)
4019        copy: whether or not to copy the expression.
4020        **opts: other options to use to parse the input expressions (again, in the case
4021            that an input expression is a SQL string).
4022
4023    Returns:
4024        Expression: the parsed or given expression.
4025    """
4026    if isinstance(sql_or_expression, Expression):
4027        if copy:
4028            return sql_or_expression.copy()
4029        return sql_or_expression
4030
4031    import sqlglot
4032
4033    sql = str(sql_or_expression)
4034    if prefix:
4035        sql = f"{prefix} {sql}"
4036    return sqlglot.parse_one(sql, read=dialect, into=into, **opts)

Gracefully handle a possible string or expression.

Example:
>>> maybe_parse("1")
(LITERAL this: 1, is_string: False)
>>> maybe_parse(to_identifier("x"))
(IDENTIFIER this: x, quoted: False)
Arguments:
  • sql_or_expression: the SQL code string or an expression
  • into: the SQLGlot Expression to parse into
  • dialect: the dialect used to parse the input expressions (in the case that an input expression is a SQL string).
  • prefix: a string to prefix the sql with before it gets parsed (automatically includes a space)
  • copy: whether or not to copy the expression.
  • **opts: other options to use to parse the input expressions (again, in the case that an input expression is a SQL string).
Returns:

Expression: the parsed or given expression.

def union(left, right, distinct=True, dialect=None, **opts):
4182def union(left, right, distinct=True, dialect=None, **opts):
4183    """
4184    Initializes a syntax tree from one UNION expression.
4185
4186    Example:
4187        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
4188        'SELECT * FROM foo UNION SELECT * FROM bla'
4189
4190    Args:
4191        left (str | Expression): the SQL code string corresponding to the left-hand side.
4192            If an `Expression` instance is passed, it will be used as-is.
4193        right (str | Expression): the SQL code string corresponding to the right-hand side.
4194            If an `Expression` instance is passed, it will be used as-is.
4195        distinct (bool): set the DISTINCT flag if and only if this is true.
4196        dialect (str): the dialect used to parse the input expression.
4197        opts (kwargs): other options to use to parse the input expressions.
4198    Returns:
4199        Union: the syntax tree for the UNION expression.
4200    """
4201    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4202    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4203
4204    return Union(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one UNION expression.

Example:
>>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo UNION SELECT * FROM bla'
Arguments:
  • left (str | Expression): the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right (str | Expression): the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Union: the syntax tree for the UNION expression.

def intersect(left, right, distinct=True, dialect=None, **opts):
4207def intersect(left, right, distinct=True, dialect=None, **opts):
4208    """
4209    Initializes a syntax tree from one INTERSECT expression.
4210
4211    Example:
4212        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
4213        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
4214
4215    Args:
4216        left (str | Expression): the SQL code string corresponding to the left-hand side.
4217            If an `Expression` instance is passed, it will be used as-is.
4218        right (str | Expression): the SQL code string corresponding to the right-hand side.
4219            If an `Expression` instance is passed, it will be used as-is.
4220        distinct (bool): set the DISTINCT flag if and only if this is true.
4221        dialect (str): the dialect used to parse the input expression.
4222        opts (kwargs): other options to use to parse the input expressions.
4223    Returns:
4224        Intersect: the syntax tree for the INTERSECT expression.
4225    """
4226    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4227    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4228
4229    return Intersect(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one INTERSECT expression.

Example:
>>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Arguments:
  • left (str | Expression): the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right (str | Expression): the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Intersect: the syntax tree for the INTERSECT expression.

def except_(left, right, distinct=True, dialect=None, **opts):
4232def except_(left, right, distinct=True, dialect=None, **opts):
4233    """
4234    Initializes a syntax tree from one EXCEPT expression.
4235
4236    Example:
4237        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
4238        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
4239
4240    Args:
4241        left (str | Expression): the SQL code string corresponding to the left-hand side.
4242            If an `Expression` instance is passed, it will be used as-is.
4243        right (str | Expression): the SQL code string corresponding to the right-hand side.
4244            If an `Expression` instance is passed, it will be used as-is.
4245        distinct (bool): set the DISTINCT flag if and only if this is true.
4246        dialect (str): the dialect used to parse the input expression.
4247        opts (kwargs): other options to use to parse the input expressions.
4248    Returns:
4249        Except: the syntax tree for the EXCEPT statement.
4250    """
4251    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4252    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4253
4254    return Except(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one EXCEPT expression.

Example:
>>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Arguments:
  • left (str | Expression): the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right (str | Expression): the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Except: the syntax tree for the EXCEPT statement.

def select( *expressions: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Select:
4257def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4258    """
4259    Initializes a syntax tree from one or multiple SELECT expressions.
4260
4261    Example:
4262        >>> select("col1", "col2").from_("tbl").sql()
4263        'SELECT col1, col2 FROM tbl'
4264
4265    Args:
4266        *expressions: the SQL code string to parse as the expressions of a
4267            SELECT statement. If an Expression instance is passed, this is used as-is.
4268        dialect: the dialect used to parse the input expressions (in the case that an
4269            input expression is a SQL string).
4270        **opts: other options to use to parse the input expressions (again, in the case
4271            that an input expression is a SQL string).
4272
4273    Returns:
4274        Select: the syntax tree for the SELECT statement.
4275    """
4276    return Select().select(*expressions, dialect=dialect, **opts)

Initializes a syntax tree from one or multiple SELECT expressions.

Example:
>>> select("col1", "col2").from_("tbl").sql()
'SELECT col1, col2 FROM tbl'
Arguments:
  • *expressions: the SQL code string to parse as the expressions of a SELECT statement. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expressions (in the case that an input expression is a SQL string).
  • **opts: other options to use to parse the input expressions (again, in the case that an input expression is a SQL string).
Returns:

Select: the syntax tree for the SELECT statement.

def from_(*expressions, dialect=None, **opts) -> sqlglot.expressions.Select:
4279def from_(*expressions, dialect=None, **opts) -> Select:
4280    """
4281    Initializes a syntax tree from a FROM expression.
4282
4283    Example:
4284        >>> from_("tbl").select("col1", "col2").sql()
4285        'SELECT col1, col2 FROM tbl'
4286
4287    Args:
4288        *expressions (str | Expression): the SQL code string to parse as the FROM expressions of a
4289            SELECT statement. If an Expression instance is passed, this is used as-is.
4290        dialect (str): the dialect used to parse the input expression (in the case that the
4291            input expression is a SQL string).
4292        **opts: other options to use to parse the input expressions (again, in the case
4293            that the input expression is a SQL string).
4294
4295    Returns:
4296        Select: the syntax tree for the SELECT statement.
4297    """
4298    return Select().from_(*expressions, dialect=dialect, **opts)

Initializes a syntax tree from a FROM expression.

Example:
>>> from_("tbl").select("col1", "col2").sql()
'SELECT col1, col2 FROM tbl'
Arguments:
  • *expressions (str | Expression): the SQL code string to parse as the FROM expressions of a SELECT statement. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression (in the case that the input expression is a SQL string).
  • **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:

Select: the syntax tree for the SELECT statement.

def update( table: str | sqlglot.expressions.Table, properties: dict, where: Union[str, sqlglot.expressions.Expression, NoneType] = None, from_: Union[str, sqlglot.expressions.Expression, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Update:
4301def update(
4302    table: str | Table,
4303    properties: dict,
4304    where: t.Optional[ExpOrStr] = None,
4305    from_: t.Optional[ExpOrStr] = None,
4306    dialect: DialectType = None,
4307    **opts,
4308) -> Update:
4309    """
4310    Creates an update statement.
4311
4312    Example:
4313        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
4314        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
4315
4316    Args:
4317        *properties: dictionary of properties to set which are
4318            auto converted to sql objects eg None -> NULL
4319        where: sql conditional parsed into a WHERE statement
4320        from_: sql statement parsed into a FROM statement
4321        dialect: the dialect used to parse the input expressions.
4322        **opts: other options to use to parse the input expressions.
4323
4324    Returns:
4325        Update: the syntax tree for the UPDATE statement.
4326    """
4327    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
4328    update_expr.set(
4329        "expressions",
4330        [
4331            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
4332            for k, v in properties.items()
4333        ],
4334    )
4335    if from_:
4336        update_expr.set(
4337            "from",
4338            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
4339        )
4340    if isinstance(where, Condition):
4341        where = Where(this=where)
4342    if where:
4343        update_expr.set(
4344            "where",
4345            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
4346        )
4347    return update_expr

Creates an update statement.

Example:
>>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
"UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
Arguments:
  • *properties: dictionary of properties to set which are auto converted to sql objects eg None -> NULL
  • where: sql conditional parsed into a WHERE statement
  • from_: sql statement parsed into a FROM statement
  • dialect: the dialect used to parse the input expressions.
  • **opts: other options to use to parse the input expressions.
Returns:

Update: the syntax tree for the UPDATE statement.

def delete( table: Union[str, sqlglot.expressions.Expression], where: Union[str, sqlglot.expressions.Expression, NoneType] = None, returning: Union[str, sqlglot.expressions.Expression, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Delete:
4350def delete(
4351    table: ExpOrStr,
4352    where: t.Optional[ExpOrStr] = None,
4353    returning: t.Optional[ExpOrStr] = None,
4354    dialect: DialectType = None,
4355    **opts,
4356) -> Delete:
4357    """
4358    Builds a delete statement.
4359
4360    Example:
4361        >>> delete("my_table", where="id > 1").sql()
4362        'DELETE FROM my_table WHERE id > 1'
4363
4364    Args:
4365        where: sql conditional parsed into a WHERE statement
4366        returning: sql conditional parsed into a RETURNING statement
4367        dialect: the dialect used to parse the input expressions.
4368        **opts: other options to use to parse the input expressions.
4369
4370    Returns:
4371        Delete: the syntax tree for the DELETE statement.
4372    """
4373    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
4374    if where:
4375        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
4376    if returning:
4377        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
4378    return delete_expr

Builds a delete statement.

Example:
>>> delete("my_table", where="id > 1").sql()
'DELETE FROM my_table WHERE id > 1'
Arguments:
  • where: sql conditional parsed into a WHERE statement
  • returning: sql conditional parsed into a RETURNING statement
  • dialect: the dialect used to parse the input expressions.
  • **opts: other options to use to parse the input expressions.
Returns:

Delete: the syntax tree for the DELETE statement.

def condition(expression, dialect=None, **opts) -> sqlglot.expressions.Condition:
4381def condition(expression, dialect=None, **opts) -> Condition:
4382    """
4383    Initialize a logical condition expression.
4384
4385    Example:
4386        >>> condition("x=1").sql()
4387        'x = 1'
4388
4389        This is helpful for composing larger logical syntax trees:
4390        >>> where = condition("x=1")
4391        >>> where = where.and_("y=1")
4392        >>> Select().from_("tbl").select("*").where(where).sql()
4393        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
4394
4395    Args:
4396        *expression (str | Expression): the SQL code string to parse.
4397            If an Expression instance is passed, this is used as-is.
4398        dialect (str): the dialect used to parse the input expression (in the case that the
4399            input expression is a SQL string).
4400        **opts: other options to use to parse the input expressions (again, in the case
4401            that the input expression is a SQL string).
4402
4403    Returns:
4404        Condition: the expression
4405    """
4406    return maybe_parse(  # type: ignore
4407        expression,
4408        into=Condition,
4409        dialect=dialect,
4410        **opts,
4411    )

Initialize a logical condition expression.

Example:
>>> condition("x=1").sql()
'x = 1'

This is helpful for composing larger logical syntax trees:

>>> where = condition("x=1")
>>> where = where.and_("y=1")
>>> Select().from_("tbl").select("*").where(where).sql()
'SELECT * FROM tbl WHERE x = 1 AND y = 1'
Arguments:
  • *expression (str | Expression): the SQL code string to parse. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression (in the case that the input expression is a SQL string).
  • **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:

Condition: the expression

def and_(*expressions, dialect=None, **opts) -> sqlglot.expressions.And:
4414def and_(*expressions, dialect=None, **opts) -> And:
4415    """
4416    Combine multiple conditions with an AND logical operator.
4417
4418    Example:
4419        >>> and_("x=1", and_("y=1", "z=1")).sql()
4420        'x = 1 AND (y = 1 AND z = 1)'
4421
4422    Args:
4423        *expressions (str | Expression): the SQL code strings to parse.
4424            If an Expression instance is passed, this is used as-is.
4425        dialect (str): the dialect used to parse the input expression.
4426        **opts: other options to use to parse the input expressions.
4427
4428    Returns:
4429        And: the new condition
4430    """
4431    return _combine(expressions, And, dialect, **opts)

Combine multiple conditions with an AND logical operator.

Example:
>>> and_("x=1", and_("y=1", "z=1")).sql()
'x = 1 AND (y = 1 AND z = 1)'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

And: the new condition

def or_(*expressions, dialect=None, **opts) -> sqlglot.expressions.Or:
4434def or_(*expressions, dialect=None, **opts) -> Or:
4435    """
4436    Combine multiple conditions with an OR logical operator.
4437
4438    Example:
4439        >>> or_("x=1", or_("y=1", "z=1")).sql()
4440        'x = 1 OR (y = 1 OR z = 1)'
4441
4442    Args:
4443        *expressions (str | Expression): the SQL code strings to parse.
4444            If an Expression instance is passed, this is used as-is.
4445        dialect (str): the dialect used to parse the input expression.
4446        **opts: other options to use to parse the input expressions.
4447
4448    Returns:
4449        Or: the new condition
4450    """
4451    return _combine(expressions, Or, dialect, **opts)

Combine multiple conditions with an OR logical operator.

Example:
>>> or_("x=1", or_("y=1", "z=1")).sql()
'x = 1 OR (y = 1 OR z = 1)'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Or: the new condition

def not_(expression, dialect=None, **opts) -> sqlglot.expressions.Not:
4454def not_(expression, dialect=None, **opts) -> Not:
4455    """
4456    Wrap a condition with a NOT operator.
4457
4458    Example:
4459        >>> not_("this_suit='black'").sql()
4460        "NOT this_suit = 'black'"
4461
4462    Args:
4463        expression (str | Expression): the SQL code strings to parse.
4464            If an Expression instance is passed, this is used as-is.
4465        dialect (str): the dialect used to parse the input expression.
4466        **opts: other options to use to parse the input expressions.
4467
4468    Returns:
4469        Not: the new condition
4470    """
4471    this = condition(
4472        expression,
4473        dialect=dialect,
4474        **opts,
4475    )
4476    return Not(this=_wrap_operator(this))

Wrap a condition with a NOT operator.

Example:
>>> not_("this_suit='black'").sql()
"NOT this_suit = 'black'"
Arguments:
  • expression (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Not: the new condition

def paren(expression) -> sqlglot.expressions.Paren:
4479def paren(expression) -> Paren:
4480    return Paren(this=expression)
def to_identifier(name, quoted=None):
4496def to_identifier(name, quoted=None):
4497    """Builds an identifier.
4498
4499    Args:
4500        name: The name to turn into an identifier.
4501        quoted: Whether or not force quote the identifier.
4502
4503    Returns:
4504        The identifier ast node.
4505    """
4506
4507    if name is None:
4508        return None
4509
4510    if isinstance(name, Identifier):
4511        identifier = name
4512    elif isinstance(name, str):
4513        identifier = Identifier(
4514            this=name,
4515            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
4516        )
4517    else:
4518        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
4519    return identifier

Builds an identifier.

Arguments:
  • name: The name to turn into an identifier.
  • quoted: Whether or not force quote the identifier.
Returns:

The identifier ast node.

def to_interval( interval: str | sqlglot.expressions.Literal) -> sqlglot.expressions.Interval:
4525def to_interval(interval: str | Literal) -> Interval:
4526    """Builds an interval expression from a string like '1 day' or '5 months'."""
4527    if isinstance(interval, Literal):
4528        if not interval.is_string:
4529            raise ValueError("Invalid interval string.")
4530
4531        interval = interval.this
4532
4533    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
4534
4535    if not interval_parts:
4536        raise ValueError("Invalid interval string.")
4537
4538    return Interval(
4539        this=Literal.string(interval_parts.group(1)),
4540        unit=Var(this=interval_parts.group(2)),
4541    )

Builds an interval expression from a string like '1 day' or '5 months'.

def to_table( sql_path: Union[str, sqlglot.expressions.Table, NoneType], **kwargs) -> Optional[sqlglot.expressions.Table]:
4554def to_table(sql_path: t.Optional[str | Table], **kwargs) -> t.Optional[Table]:
4555    """
4556    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
4557    If a table is passed in then that table is returned.
4558
4559    Args:
4560        sql_path: a `[catalog].[schema].[table]` string.
4561
4562    Returns:
4563        A table expression.
4564    """
4565    if sql_path is None or isinstance(sql_path, Table):
4566        return sql_path
4567    if not isinstance(sql_path, str):
4568        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
4569
4570    catalog, db, table_name = (to_identifier(x) for x in split_num_words(sql_path, ".", 3))
4571    return Table(this=table_name, db=db, catalog=catalog, **kwargs)

Create a table expression from a [catalog].[schema].[table] sql path. Catalog and schema are optional. If a table is passed in then that table is returned.

Arguments:
  • sql_path: a [catalog].[schema].[table] string.
Returns:

A table expression.

def to_column( sql_path: str | sqlglot.expressions.Column, **kwargs) -> sqlglot.expressions.Column:
4574def to_column(sql_path: str | Column, **kwargs) -> Column:
4575    """
4576    Create a column from a `[table].[column]` sql path. Schema is optional.
4577
4578    If a column is passed in then that column is returned.
4579
4580    Args:
4581        sql_path: `[table].[column]` string
4582    Returns:
4583        Table: A column expression
4584    """
4585    if sql_path is None or isinstance(sql_path, Column):
4586        return sql_path
4587    if not isinstance(sql_path, str):
4588        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
4589    return column(*reversed(sql_path.split(".")), **kwargs)  # type: ignore

Create a column from a [table].[column] sql path. Schema is optional.

If a column is passed in then that column is returned.

Arguments:
  • sql_path: [table].[column] string
Returns:

Table: A column expression

def alias_( expression: Union[str, sqlglot.expressions.Expression], alias: str | sqlglot.expressions.Identifier, table: Union[bool, Sequence[str | sqlglot.expressions.Identifier]] = False, quoted: Optional[bool] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts):
4592def alias_(
4593    expression: ExpOrStr,
4594    alias: str | Identifier,
4595    table: bool | t.Sequence[str | Identifier] = False,
4596    quoted: t.Optional[bool] = None,
4597    dialect: DialectType = None,
4598    **opts,
4599):
4600    """Create an Alias expression.
4601
4602    Example:
4603        >>> alias_('foo', 'bar').sql()
4604        'foo AS bar'
4605
4606        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
4607        '(SELECT 1, 2) AS bar(a, b)'
4608
4609    Args:
4610        expression: the SQL code strings to parse.
4611            If an Expression instance is passed, this is used as-is.
4612        alias: the alias name to use. If the name has
4613            special characters it is quoted.
4614        table: Whether or not to create a table alias, can also be a list of columns.
4615        quoted: whether or not to quote the alias
4616        dialect: the dialect used to parse the input expression.
4617        **opts: other options to use to parse the input expressions.
4618
4619    Returns:
4620        Alias: the aliased expression
4621    """
4622    exp = maybe_parse(expression, dialect=dialect, **opts)
4623    alias = to_identifier(alias, quoted=quoted)
4624
4625    if table:
4626        table_alias = TableAlias(this=alias)
4627        exp.set("alias", table_alias)
4628
4629        if not isinstance(table, bool):
4630            for column in table:
4631                table_alias.append("columns", to_identifier(column, quoted=quoted))
4632
4633        return exp
4634
4635    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
4636    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
4637    # for the complete Window expression.
4638    #
4639    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
4640
4641    if "alias" in exp.arg_types and not isinstance(exp, Window):
4642        exp = exp.copy()
4643        exp.set("alias", alias)
4644        return exp
4645    return Alias(this=exp, alias=alias)

Create an Alias expression.

Example:
>>> alias_('foo', 'bar').sql()
'foo AS bar'
>>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
'(SELECT 1, 2) AS bar(a, b)'
Arguments:
  • expression: the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • alias: the alias name to use. If the name has special characters it is quoted.
  • table: Whether or not to create a table alias, can also be a list of columns.
  • quoted: whether or not to quote the alias
  • dialect: the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Alias: the aliased expression

def subquery(expression, alias=None, dialect=None, **opts):
4648def subquery(expression, alias=None, dialect=None, **opts):
4649    """
4650    Build a subquery expression.
4651
4652    Example:
4653        >>> subquery('select x from tbl', 'bar').select('x').sql()
4654        'SELECT x FROM (SELECT x FROM tbl) AS bar'
4655
4656    Args:
4657        expression (str | Expression): the SQL code strings to parse.
4658            If an Expression instance is passed, this is used as-is.
4659        alias (str | Expression): the alias name to use.
4660        dialect (str): the dialect used to parse the input expression.
4661        **opts: other options to use to parse the input expressions.
4662
4663    Returns:
4664        Select: a new select with the subquery expression included
4665    """
4666
4667    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
4668    return Select().from_(expression, dialect=dialect, **opts)

Build a subquery expression.

Example:
>>> subquery('select x from tbl', 'bar').select('x').sql()
'SELECT x FROM (SELECT x FROM tbl) AS bar'
Arguments:
  • expression (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • alias (str | Expression): the alias name to use.
  • dialect (str): the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Select: a new select with the subquery expression included

def column( col: str | sqlglot.expressions.Identifier, table: Union[str, sqlglot.expressions.Identifier, NoneType] = None, db: Union[str, sqlglot.expressions.Identifier, NoneType] = None, catalog: Union[str, sqlglot.expressions.Identifier, NoneType] = None, quoted: Optional[bool] = None) -> sqlglot.expressions.Column:
4671def column(
4672    col: str | Identifier,
4673    table: t.Optional[str | Identifier] = None,
4674    db: t.Optional[str | Identifier] = None,
4675    catalog: t.Optional[str | Identifier] = None,
4676    quoted: t.Optional[bool] = None,
4677) -> Column:
4678    """
4679    Build a Column.
4680
4681    Args:
4682        col: column name
4683        table: table name
4684        db: db name
4685        catalog: catalog name
4686        quoted: whether or not to force quote each part
4687    Returns:
4688        Column: column instance
4689    """
4690    return Column(
4691        this=to_identifier(col, quoted=quoted),
4692        table=to_identifier(table, quoted=quoted),
4693        db=to_identifier(db, quoted=quoted),
4694        catalog=to_identifier(catalog, quoted=quoted),
4695    )

Build a Column.

Arguments:
  • col: column name
  • table: table name
  • db: db name
  • catalog: catalog name
  • quoted: whether or not to force quote each part
Returns:

Column: column instance

def cast( expression: Union[str, sqlglot.expressions.Expression], to: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type, **opts) -> sqlglot.expressions.Cast:
4698def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
4699    """Cast an expression to a data type.
4700
4701    Example:
4702        >>> cast('x + 1', 'int').sql()
4703        'CAST(x + 1 AS INT)'
4704
4705    Args:
4706        expression: The expression to cast.
4707        to: The datatype to cast to.
4708
4709    Returns:
4710        A cast node.
4711    """
4712    expression = maybe_parse(expression, **opts)
4713    return Cast(this=expression, to=DataType.build(to, **opts))

Cast an expression to a data type.

Example:
>>> cast('x + 1', 'int').sql()
'CAST(x + 1 AS INT)'
Arguments:
  • expression: The expression to cast.
  • to: The datatype to cast to.
Returns:

A cast node.

def table_( table, db=None, catalog=None, quoted=None, alias=None) -> sqlglot.expressions.Table:
4716def table_(table, db=None, catalog=None, quoted=None, alias=None) -> Table:
4717    """Build a Table.
4718
4719    Args:
4720        table (str | Expression): column name
4721        db (str | Expression): db name
4722        catalog (str | Expression): catalog name
4723
4724    Returns:
4725        Table: table instance
4726    """
4727    return Table(
4728        this=to_identifier(table, quoted=quoted),
4729        db=to_identifier(db, quoted=quoted),
4730        catalog=to_identifier(catalog, quoted=quoted),
4731        alias=TableAlias(this=to_identifier(alias)) if alias else None,
4732    )

Build a Table.

Arguments:
  • table (str | Expression): column name
  • db (str | Expression): db name
  • catalog (str | Expression): catalog name
Returns:

Table: table instance

def values( values: Iterable[Tuple[Any, ...]], alias: Optional[str] = None, columns: Union[Iterable[str], Dict[str, sqlglot.expressions.DataType], NoneType] = None) -> sqlglot.expressions.Values:
4735def values(
4736    values: t.Iterable[t.Tuple[t.Any, ...]],
4737    alias: t.Optional[str] = None,
4738    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
4739) -> Values:
4740    """Build VALUES statement.
4741
4742    Example:
4743        >>> values([(1, '2')]).sql()
4744        "VALUES (1, '2')"
4745
4746    Args:
4747        values: values statements that will be converted to SQL
4748        alias: optional alias
4749        columns: Optional list of ordered column names or ordered dictionary of column names to types.
4750         If either are provided then an alias is also required.
4751         If a dictionary is provided then the first column of the values will be casted to the expected type
4752         in order to help with type inference.
4753
4754    Returns:
4755        Values: the Values expression object
4756    """
4757    if columns and not alias:
4758        raise ValueError("Alias is required when providing columns")
4759    table_alias = (
4760        TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
4761        if columns
4762        else TableAlias(this=to_identifier(alias) if alias else None)
4763    )
4764    expressions = [convert(tup) for tup in values]
4765    if columns and isinstance(columns, dict):
4766        types = list(columns.values())
4767        expressions[0].set(
4768            "expressions",
4769            [cast(x, types[i]) for i, x in enumerate(expressions[0].expressions)],
4770        )
4771    return Values(
4772        expressions=expressions,
4773        alias=table_alias,
4774    )

Build VALUES statement.

Example:
>>> values([(1, '2')]).sql()
"VALUES (1, '2')"
Arguments:
  • values: values statements that will be converted to SQL
  • alias: optional alias
  • columns: Optional list of ordered column names or ordered dictionary of column names to types. If either are provided then an alias is also required. If a dictionary is provided then the first column of the values will be casted to the expected type in order to help with type inference.
Returns:

Values: the Values expression object

def var( name: Union[str, sqlglot.expressions.Expression, NoneType]) -> sqlglot.expressions.Var:
4777def var(name: t.Optional[ExpOrStr]) -> Var:
4778    """Build a SQL variable.
4779
4780    Example:
4781        >>> repr(var('x'))
4782        '(VAR this: x)'
4783
4784        >>> repr(var(column('x', table='y')))
4785        '(VAR this: x)'
4786
4787    Args:
4788        name: The name of the var or an expression who's name will become the var.
4789
4790    Returns:
4791        The new variable node.
4792    """
4793    if not name:
4794        raise ValueError("Cannot convert empty name into var.")
4795
4796    if isinstance(name, Expression):
4797        name = name.name
4798    return Var(this=name)

Build a SQL variable.

Example:
>>> repr(var('x'))
'(VAR this: x)'
>>> repr(var(column('x', table='y')))
'(VAR this: x)'
Arguments:
  • name: The name of the var or an expression who's name will become the var.
Returns:

The new variable node.

def rename_table( old_name: str | sqlglot.expressions.Table, new_name: str | sqlglot.expressions.Table) -> sqlglot.expressions.AlterTable:
4801def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
4802    """Build ALTER TABLE... RENAME... expression
4803
4804    Args:
4805        old_name: The old name of the table
4806        new_name: The new name of the table
4807
4808    Returns:
4809        Alter table expression
4810    """
4811    old_table = to_table(old_name)
4812    new_table = to_table(new_name)
4813    return AlterTable(
4814        this=old_table,
4815        actions=[
4816            RenameTable(this=new_table),
4817        ],
4818    )

Build ALTER TABLE... RENAME... expression

Arguments:
  • old_name: The old name of the table
  • new_name: The new name of the table
Returns:

Alter table expression

def convert(value) -> sqlglot.expressions.Expression:
4821def convert(value) -> Expression:
4822    """Convert a python value into an expression object.
4823
4824    Raises an error if a conversion is not possible.
4825
4826    Args:
4827        value (Any): a python object
4828
4829    Returns:
4830        Expression: the equivalent expression object
4831    """
4832    if isinstance(value, Expression):
4833        return value
4834    if value is None:
4835        return NULL
4836    if isinstance(value, bool):
4837        return Boolean(this=value)
4838    if isinstance(value, str):
4839        return Literal.string(value)
4840    if isinstance(value, float) and math.isnan(value):
4841        return NULL
4842    if isinstance(value, numbers.Number):
4843        return Literal.number(value)
4844    if isinstance(value, tuple):
4845        return Tuple(expressions=[convert(v) for v in value])
4846    if isinstance(value, list):
4847        return Array(expressions=[convert(v) for v in value])
4848    if isinstance(value, dict):
4849        return Map(
4850            keys=[convert(k) for k in value],
4851            values=[convert(v) for v in value.values()],
4852        )
4853    if isinstance(value, datetime.datetime):
4854        datetime_literal = Literal.string(
4855            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
4856        )
4857        return TimeStrToTime(this=datetime_literal)
4858    if isinstance(value, datetime.date):
4859        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
4860        return DateStrToDate(this=date_literal)
4861    raise ValueError(f"Cannot convert {value}")

Convert a python value into an expression object.

Raises an error if a conversion is not possible.

Arguments:
  • value (Any): a python object
Returns:

Expression: the equivalent expression object

def replace_children(expression, fun, *args, **kwargs):
4864def replace_children(expression, fun, *args, **kwargs):
4865    """
4866    Replace children of an expression with the result of a lambda fun(child) -> exp.
4867    """
4868    for k, v in expression.args.items():
4869        is_list_arg = type(v) is list
4870
4871        child_nodes = v if is_list_arg else [v]
4872        new_child_nodes = []
4873
4874        for cn in child_nodes:
4875            if isinstance(cn, Expression):
4876                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
4877                    new_child_nodes.append(child_node)
4878                    child_node.parent = expression
4879                    child_node.arg_key = k
4880            else:
4881                new_child_nodes.append(cn)
4882
4883        expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0)

Replace children of an expression with the result of a lambda fun(child) -> exp.

def column_table_names(expression):
4886def column_table_names(expression):
4887    """
4888    Return all table names referenced through columns in an expression.
4889
4890    Example:
4891        >>> import sqlglot
4892        >>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e"))
4893        ['c', 'a']
4894
4895    Args:
4896        expression (sqlglot.Expression): expression to find table names
4897
4898    Returns:
4899        list: A list of unique names
4900    """
4901    return list(dict.fromkeys(column.table for column in expression.find_all(Column)))

Return all table names referenced through columns in an expression.

Example:
>>> import sqlglot
>>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e"))
['c', 'a']
Arguments:
  • expression (sqlglot.Expression): expression to find table names
Returns:

list: A list of unique names

def table_name(table) -> str:
4904def table_name(table) -> str:
4905    """Get the full name of a table as a string.
4906
4907    Args:
4908        table (exp.Table | str): table expression node or string.
4909
4910    Examples:
4911        >>> from sqlglot import exp, parse_one
4912        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
4913        'a.b.c'
4914
4915    Returns:
4916        The table name.
4917    """
4918
4919    table = maybe_parse(table, into=Table)
4920
4921    if not table:
4922        raise ValueError(f"Cannot parse {table}")
4923
4924    return ".".join(
4925        part
4926        for part in (
4927            table.text("catalog"),
4928            table.text("db"),
4929            table.name,
4930        )
4931        if part
4932    )

Get the full name of a table as a string.

Arguments:
  • table (exp.Table | str): table expression node or string.
Examples:
>>> from sqlglot import exp, parse_one
>>> table_name(parse_one("select * from a.b.c").find(exp.Table))
'a.b.c'
Returns:

The table name.

def replace_tables(expression, mapping):
4935def replace_tables(expression, mapping):
4936    """Replace all tables in expression according to the mapping.
4937
4938    Args:
4939        expression (sqlglot.Expression): expression node to be transformed and replaced.
4940        mapping (Dict[str, str]): mapping of table names.
4941
4942    Examples:
4943        >>> from sqlglot import exp, parse_one
4944        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
4945        'SELECT * FROM c'
4946
4947    Returns:
4948        The mapped expression.
4949    """
4950
4951    def _replace_tables(node):
4952        if isinstance(node, Table):
4953            new_name = mapping.get(table_name(node))
4954            if new_name:
4955                return to_table(
4956                    new_name,
4957                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
4958                )
4959        return node
4960
4961    return expression.transform(_replace_tables)

Replace all tables in expression according to the mapping.

Arguments:
  • expression (sqlglot.Expression): expression node to be transformed and replaced.
  • mapping (Dict[str, str]): mapping of table names.
Examples:
>>> from sqlglot import exp, parse_one
>>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
'SELECT * FROM c'
Returns:

The mapped expression.

def replace_placeholders(expression, *args, **kwargs):
4964def replace_placeholders(expression, *args, **kwargs):
4965    """Replace placeholders in an expression.
4966
4967    Args:
4968        expression (sqlglot.Expression): expression node to be transformed and replaced.
4969        args: positional names that will substitute unnamed placeholders in the given order.
4970        kwargs: keyword arguments that will substitute named placeholders.
4971
4972    Examples:
4973        >>> from sqlglot import exp, parse_one
4974        >>> replace_placeholders(
4975        ...     parse_one("select * from :tbl where ? = ?"), "a", "b", tbl="foo"
4976        ... ).sql()
4977        'SELECT * FROM foo WHERE a = b'
4978
4979    Returns:
4980        The mapped expression.
4981    """
4982
4983    def _replace_placeholders(node, args, **kwargs):
4984        if isinstance(node, Placeholder):
4985            if node.name:
4986                new_name = kwargs.get(node.name)
4987                if new_name:
4988                    return to_identifier(new_name)
4989            else:
4990                try:
4991                    return to_identifier(next(args))
4992                except StopIteration:
4993                    pass
4994        return node
4995
4996    return expression.transform(_replace_placeholders, iter(args), **kwargs)

Replace placeholders in an expression.

Arguments:
  • expression (sqlglot.Expression): expression node to be transformed and replaced.
  • args: positional names that will substitute unnamed placeholders in the given order.
  • kwargs: keyword arguments that will substitute named placeholders.
Examples:
>>> from sqlglot import exp, parse_one
>>> replace_placeholders(
...     parse_one("select * from :tbl where ? = ?"), "a", "b", tbl="foo"
... ).sql()
'SELECT * FROM foo WHERE a = b'
Returns:

The mapped expression.

def expand( expression: sqlglot.expressions.Expression, sources: Dict[str, sqlglot.expressions.Subqueryable], copy=True) -> sqlglot.expressions.Expression:
4999def expand(expression: Expression, sources: t.Dict[str, Subqueryable], copy=True) -> Expression:
5000    """Transforms an expression by expanding all referenced sources into subqueries.
5001
5002    Examples:
5003        >>> from sqlglot import parse_one
5004        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
5005        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
5006
5007    Args:
5008        expression: The expression to expand.
5009        sources: A dictionary of name to Subqueryables.
5010        copy: Whether or not to copy the expression during transformation. Defaults to True.
5011
5012    Returns:
5013        The transformed expression.
5014    """
5015
5016    def _expand(node: Expression):
5017        if isinstance(node, Table):
5018            name = table_name(node)
5019            source = sources.get(name)
5020            if source:
5021                subquery = source.subquery(node.alias or name)
5022                subquery.comments = [f"source: {name}"]
5023                return subquery
5024        return node
5025
5026    return expression.transform(_expand, copy=copy)

Transforms an expression by expanding all referenced sources into subqueries.

Examples:
>>> from sqlglot import parse_one
>>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
Arguments:
  • expression: The expression to expand.
  • sources: A dictionary of name to Subqueryables.
  • copy: Whether or not to copy the expression during transformation. Defaults to True.
Returns:

The transformed expression.

def func( name: str, *args, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> sqlglot.expressions.Func:
5029def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
5030    """
5031    Returns a Func expression.
5032
5033    Examples:
5034        >>> func("abs", 5).sql()
5035        'ABS(5)'
5036
5037        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
5038        'CAST(5 AS DOUBLE)'
5039
5040    Args:
5041        name: the name of the function to build.
5042        args: the args used to instantiate the function of interest.
5043        dialect: the source dialect.
5044        kwargs: the kwargs used to instantiate the function of interest.
5045
5046    Note:
5047        The arguments `args` and `kwargs` are mutually exclusive.
5048
5049    Returns:
5050        An instance of the function of interest, or an anonymous function, if `name` doesn't
5051        correspond to an existing `sqlglot.expressions.Func` class.
5052    """
5053    if args and kwargs:
5054        raise ValueError("Can't use both args and kwargs to instantiate a function.")
5055
5056    from sqlglot.dialects.dialect import Dialect
5057
5058    converted = [convert(arg) for arg in args]
5059    kwargs = {key: convert(value) for key, value in kwargs.items()}
5060
5061    parser = Dialect.get_or_raise(dialect)().parser()
5062    from_args_list = parser.FUNCTIONS.get(name.upper())
5063
5064    if from_args_list:
5065        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
5066    else:
5067        kwargs = kwargs or {"expressions": converted}
5068        function = Anonymous(this=name, **kwargs)
5069
5070    for error_message in function.error_messages(converted):
5071        raise ValueError(error_message)
5072
5073    return function

Returns a Func expression.

Examples:
>>> func("abs", 5).sql()
'ABS(5)'
>>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
'CAST(5 AS DOUBLE)'
Arguments:
  • name: the name of the function to build.
  • args: the args used to instantiate the function of interest.
  • dialect: the source dialect.
  • kwargs: the kwargs used to instantiate the function of interest.
Note:

The arguments args and kwargs are mutually exclusive.

Returns:

An instance of the function of interest, or an anonymous function, if name doesn't correspond to an existing sqlglot.expressions.Func class.

def true():
5076def true():
5077    """
5078    Returns a true Boolean expression.
5079    """
5080    return Boolean(this=True)

Returns a true Boolean expression.

def false():
5083def false():
5084    """
5085    Returns a false Boolean expression.
5086    """
5087    return Boolean(this=False)

Returns a false Boolean expression.

def null():
5090def null():
5091    """
5092    Returns a Null expression.
5093    """
5094    return Null()

Returns a Null expression.